显示图库中的图像 - 仅在模拟器上工作

时间:2016-06-03 07:33:21

标签: android image android-intent

我是Android开发的初学者,很抱歉如果我在这里发帖时犯了一些错误。 我一直在学习捕捉或选择图像并在ImageView中显示的教程。 如果我从相机捕获图像,或选择以前从相机捕获的图像,一切都有效。 如果我在内部或外部存储器中选择任何图像,则无法显示。

在具有不同配置的模拟器中,它始终有效。 我真正的测试设备是带有cyanogenmod android 5.1的三星galaxy 4

在清单中我添加了

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我要捕获或选择的代码是:

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class selectImage extends Activity {

    private final int REQUEST_CAMERA = 0;
    private final int SELECT_FILE = 1;
    private ImageView ivImage;
    private String userChosenTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_image);
        Button btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
        btnSelect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                setImage();
            }
        });
        ivImage = (ImageView) findViewById(R.id.ivImage);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if(userChosenTask.equals("Take Photo"))
                        cameraIntent();
                    else if(userChosenTask.equals("Choose from Library"))
                        galleryIntent();
                } else {
                    //code for deny
                }
                break;
        }
    }

    private void setImage() {
        final CharSequence[] items = { "Take Photo", "Choose from Library",
                "Cancel" };
                AlertDialog.Builder builder = new AlertDialog.Builder(selectImage.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result=Utility.checkPermission(selectImage.this);

                if (items[item].equals("Take Photo")) {
                    userChosenTask ="Take Photo";
                    if(result)
                        cameraIntent();

                } else if (items[item].equals("Choose from Library")) {
                    userChosenTask ="Choose from Library";
                    if(result)
                        galleryIntent();

                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    private void galleryIntent()
    {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_PICK);//
        startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
    }

    private void cameraIntent()
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == SELECT_FILE)

                onSelectFromGalleryResult(data);

            }
        else if (requestCode == REQUEST_CAMERA){
            onCaptureImageResult(data);
    }
}


private void onCaptureImageResult(Intent data) {
    Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    assert thumbnail != null;
    thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    File destination = new File(Environment.getExternalStorageDirectory(),
            System.currentTimeMillis() + ".jpg");

    FileOutputStream fo;
    try {
        destination.createNewFile();
        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
        fo.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    ivImage.setImageBitmap(thumbnail);
}

@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
    Bitmap bm=null;
    if (data != null) {
        try {

            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    ivImage.setImageBitmap(bm);
}

}

因此,在模拟器上它总是工作,在真实设备上相机意图工作,我可以保存图片。只有当我选择通过此测试应用程序的相机意图保存的图像时,图库意图才有效,否则我会得到空白的图像视图,没有任何显示。

我想知道它是否可能是一个权限问题,即使我把它放在清单中? 我还尝试了在stackexchange上找到的其他代码,但遇到了同样的问题。

有关如何解决此问题的任何提示都很受欢迎。

我一直关注的教程如下: http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample

0 个答案:

没有答案