从Uri获取位图

时间:2017-03-09 09:03:15

标签: java android android-bitmap

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_image);

   imageView = (ImageView) findViewById(R.id.imageView);

    Intent intent = getIntent();
    Uri imageUri = intent.getData();
   // Picasso.with(this).load(imageUri).into(imageView);

    if(imageUri == null){
        Log.d(TAG, "Check");
    }






        //BitmapFactory.Options options = new BitmapFactory.Options();
     //   options.inSampleSize = 8;
     //   bm = MediaStore.Images.Media.getBitmap(getContentResolver(),imageUri);

    Bitmap bm = null;

    try{
        InputStream image;
    try{
        image = getContentResolver().openInputStream(imageUri);
        bm = BitmapFactory.decodeStream(image);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    }
    catch (Exception e){
        e.printStackTrace();
    }




    //BitmapFactory.Options options = new BitmapFactory.Options();
   // bm = BitmapFactory.decodeFile(file.getAbsolutePath(),options);


    if ((bm == null)) {
        prints("It doesn't work");
    }

    //Log.d(TAG,"Going to convert image.");
      imageView.setImageBitmap(bm);

我已经查看了一堆StackOverFlow问题,我已经尝试了所有问题,正如您在评论代码中看到的那样。我试图在拍摄照片时获得一个未更改的位图。位图的像素位置对我的目标至关重要。图像质量很高,可能是更大的文件。我的位图始终为空,我确保我的Uri不是。有任何想法吗?

3 个答案:

答案 0 :(得分:2)

我认为以下代码可以帮助您

  private void setImage(String path, CircleImageView img) {

    options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .cacheOnDisk(true)
            .considerExifParams(true)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .showImageOnLoading(R.drawable.user)
            .showImageForEmptyUri(R.drawable.user)
            .showImageOnFail(R.drawable.user)
            .build();

    ImageLoader.getInstance().displayImage(path, img, options, new SimpleImageLoadingListener() {

        @Override
        public void onLoadingStarted(String imageUri, View view) {
            super.onLoadingStarted(imageUri, view);
        }

        @Override
        public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
            super.onLoadingFailed(imageUri, view, failReason);
        }

        @Override
        public void onLoadingCancelled(String imageUri, View view) {
            super.onLoadingCancelled(imageUri, view);
        }

        @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
            super.onLoadingComplete(imageUri, view, loadedImage);
        }
    }, new ImageLoadingProgressListener() {
        @Override
        public void onProgressUpdate(String s, View view, int i, int i1) {

        }
    });
}

SimpleImageLoadingListener()

使用通用图片加载器

答案 1 :(得分:0)

该文件的分辨率太大,无法制作位图。没有足够的内存来构造位图,因此返回null。

尝试使用非常小的图像文件查看。

答案 2 :(得分:0)

如果来自您的移动存储设备,您可以直接从URI获取Bitmap。

public Bitmap getBitmapFromURI(Uri uri){
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(uri, filePathColumn, null, null, null);
        if(cursor!=null){
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            File f_image = new File(cursor.getString(columnIndex));
            cursor.close();
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            return BitmapFactory.decodeFile(f_image.getAbsolutePath(), o2);
        }
        return null;
    }

如果文件太大而无法加载..您需要压缩图像并显示。为此,您还需要使用异步任务。

我制作了一个Image压缩器任务,你可以将它用于大图像

public class ConvertBase64Task extends AsyncTask<Void, Bitmap, Bitmap> {

    private ByteArrayOutputStream baos = new ByteArrayOutputStream();
    private File file;

    private int CompressionRatio = 80; //You can change it by what ever ratio you want. in 0 to 100.

    private boolean shouldrotate = true;





    private ImageCompressiorListner imageCompressiorListner;

    public ConvertBase64Task(File file) {
        this.file = file;
    }

    public void setRotation(boolean isRotate) {
        shouldrotate = isRotate;
    }


    public void setCompressionRatio(int Ratio) {
        CompressionRatio = Ratio;
    }


    public void setImageCompressiorListner(ImageCompressiorListner imageCompressiorListner) {
        this.imageCompressiorListner = imageCompressiorListner;
    }

    @Override
    protected void onPreExecute(){
    }

    @Override
    protected Bitmap doInBackground(Void... params) {



            try {
                //***** Fatching file
                //*****Code for Orientation
                Matrix matrix = new Matrix();

                if (shouldrotate) {
                    ExifInterface exif1 = new ExifInterface(file.getAbsolutePath());
                    int orientation = exif1.getAttributeInt(
                            ExifInterface.TAG_ORIENTATION, 1);
                    Log.d("EXIF", "Exif: " + orientation);
                    if (orientation == 6) {
                        matrix.postRotate(90);
                    } else if (orientation == 3) {
                        matrix.postRotate(180);
                    } else if (orientation == 8) {
                        matrix.postRotate(270);
                    } else {
                        matrix.postRotate(0);
                    }
                } else {
                    matrix.postRotate(0);
                }

                try {

                    BitmapFactory.Options option = new BitmapFactory.Options();
                    option.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(file.getAbsolutePath(), option);

                    int file_size = Integer.parseInt(String.valueOf(file.length() / 1024));
                    Log.e("ImageSize", "" + file_size);


                    int scale = 1;

                    if (file_size < 512) {
                        Log.e("image size is good", "image size is less");
                    } else if (file_size < 1024) {
                        Log.e("image size is 1 mb", "image size is heavy");
                        scale = 2;
                    } else if (file_size < 1536) {
                        Log.e("image size is 1.5 mb", "image size is heavy");
                        scale = 2;
                    } else if (file_size < 2048) {
                        Log.e("image size is 2 mb", "image size is heavy");
                        scale = 4;
                    } else {
                        Log.e("image size > 2 mb", "image size is heavy");
                        scale = 4;
                    }

                    Log.e("Scale", "Finaly Scaling with " + scale);

                    BitmapFactory.Options o2 = new BitmapFactory.Options();
                    o2.inSampleSize = scale;
                    Bitmap pickimg = BitmapFactory.decodeFile(file.getAbsolutePath(), o2);

                    if (pickimg.getWidth() > 1280 || pickimg.getHeight() > 1000) {

                        int width = pickimg.getWidth();
                        int height = pickimg.getHeight();

                        while (width > 1280 || height > 700) {
                            width = (width * 90) / 100;
                            height = (height * 90) / 100;
                        }

                        pickimg = Bitmap.createScaledBitmap(pickimg, width, height, true);
                    } else {
                        pickimg = Bitmap.createBitmap(pickimg, 0, 0, pickimg.getWidth(), pickimg.getHeight(), matrix, true); // rotating bitmap
                    }

                    pickimg.compress(Bitmap.CompressFormat.JPEG, CompressionRatio, baos);
                    return pickimg;

                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;

                }

            } catch (Throwable e) {
                e.printStackTrace();
                return null;
            }

    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        if (result != null) {
            if(imageCompressiorListner!=null){
                imageCompressiorListner.onImageCompressed(result);
            }
        } else {
            if(imageCompressiorListner!=null){
                imageCompressiorListner.onError();
            }
        }
    }


    public interface ImageCompressiorListner {
        void onImageCompressed(Bitmap bitmap);
        void onError();
    }
}

您可以使用以下

ConvertBase64Task task = new ConvertBase64Task(File Object of Image);
        task.setImageCompressiorListner(new ConvertBase64Task.ImageCompressiorListner() {
        @Override
        public void onImageCompressed(Bitmap bitmap) {

        }

        @Override
        public void onError() {

        }
    });
    task.execute();

希望这会帮助你。