如何将URI转换为位图?

时间:2018-02-11 07:07:15

标签: java android bitmap nullpointerexception crop

我正在制作图像过滤器应用程序并在应用过滤器之前我将图像裁剪为正方形,我可以使用Soundcloud库裁剪图像像这样: -

     @Override
    protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filter_image);

        String uri = getIntent().getStringExtra("output_image");
        setImageDir(uri);
}

在NextImageActivity.java的下一个活动上: -

 private void setImageDir(String uri)
    {
        Bitmap bitmap = convetBitmap(uri);

        // clear bitmap memory
       /* originalImage.recycle();
        finalImage.recycle();
        finalImage.recycle();*/

        originalImage = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        filteredImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
        finalImage = originalImage.copy(Bitmap.Config.ARGB_8888, true);
        imagePreview.setImageBitmap(originalImage);
        bitmap.recycle();

        // render selected image thumbnails
        filtersListFragment.prepareThumbnail(originalImage);
    }

和函数setImageDir(): -

 private Bitmap convetBitmap(final String uri)
   {
       final Bitmap[] bitmap = {null};
       Thread task = new Thread()
       {
           @Override
           public void run()
           {
               try {
                   bitmap[0] =   Glide.with(getApplicationContext()).asBitmap().load(Uri.parse(uri)).into(100,100).get();
               } catch (InterruptedException | ExecutionException e) {
                   e.printStackTrace();
               }
           }
       };

       task.start();


   return bitmap[0];

和函数convertBitmap(): -

 Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)' on a null object reference

}

图像被裁剪并保存到目录中

  

文件:///data/user/0/com.dev.pigeon/cache/cropped1518332591373

但它给出了错误

import sys

file_url = "http://"+str(sys.argv[1])+":5000/fileW"
print(file_url)
x=raw_input()

也许URI没有转换成位图请任何解决方案???

1 个答案:

答案 0 :(得分:7)

要将URI转换为位图,您可以执行以下操作。

try {
    if(  Uri.parse(paths)!=null   ){  
     Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));
        }
   }
   catch (Exception e) {
            //handle exception
        }

当你获得文件格式文件选择器或摄像头意图时,你可以这样做。

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Uri imageUri = data.getData();
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    }
}