【问题标题】:Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?从 sdcard 将图像文件读入位图,为什么会出现 NullPointerException?
【发布时间】:2012-02-01 09:20:34
【问题描述】:

如何将图像文件从 sdcard 读入位图?

 _path = Environment.getExternalStorageDirectory().getAbsolutePath();  

System.out.println("pathhhhhhhhhhhhhhhhhhhh1111111112222222 " + _path);  
_path= _path + "/" + "flower2.jpg";  
System.out.println("pathhhhhhhhhhhhhhhhhhhh111111111 " + _path);  
Bitmap bitmap = BitmapFactory.decodeFile(_path, options );  

我得到了位图的 NullPointerException。这意味着位图为空。但我有一个图像“.jpg”文件存储在 sdcard 中作为“flower2.jpg”。有什么问题?

【问题讨论】:

    标签: android android-sdcard android-image


    【解决方案1】:

    MediaStore API 可能会丢弃 alpha 通道(即解码为 RGB565)。如果你有文件路径,直接使用 BitmapFactory,但告诉它使用保留 alpha 的格式:

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
    selected_photo.setImageBitmap(bitmap);
    

    http://mihaifonoage.blogspot.com/2009/09/displaying-images-from-sd-card-in.html

    【讨论】:

    • 这里的selected_photo 是什么?
    • 嗨!相册中保存的图片是3840x2160,但是通过这种方式上传到服务器的图片是1080x1920
    • @ParagS.Chandakkar 它可能是一个 ImageView,您可以在其中显示解码的文件。
    【解决方案2】:

    有效:

    Bitmap bitmap = BitmapFactory.decodeFile(filePath);
    

    【讨论】:

      【解决方案3】:

      试试这个代码:

      Bitmap bitmap = null;
      File f = new File(_path);
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inPreferredConfig = Bitmap.Config.ARGB_8888;
      try {
          bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      }         
      image.setImageBitmap(bitmap);
      

      【讨论】:

        【解决方案4】:

        我编写了以下代码将图像从 sdcard 转换为 Base64 编码字符串以作为 JSON 对象发送。而且效果很好:

        String filepath = "/sdcard/temp.png";
        File imagefile = new File(filepath);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(imagefile);
            } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        
        Bitmap bm = BitmapFactory.decodeStream(fis);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
        byte[] b = baos.toByteArray(); 
        encImage = Base64.encodeToString(b, Base64.DEFAULT);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多