Load bitmap from file Android

本文介绍了一种在Android中加载图片文件为Bitmap时遇到的问题及其解决方案。主要讨论了当使用BitmapFactory.decodeFile方法加载图片时返回null的情况,并提供了解决方案,即通过设置BitmapFactory.Options来指定图片的配置。

public static Bitmap loadFromFile(String filename) {
      try {
          File f = new File(filename);
          if (!f.exists()) { return null; }
          Bitmap tmp = BitmapFactory.decodeFile(filename);
          return tmp;
      } catch (Exception e) {
          return null;
      }
  }

 

import java.io.File;
import java.io.FileOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;

class PictUtil {
  public static File getSavePath() {
      File path;
      if (hasSDCard()) { // SD card
          path = new File(getSDCardPath() + "/Tegaky/");
          path.mkdir();
      } else { 
          path = Environment.getDataDirectory();
      }
      return path;
  }
  public static String getCacheFilename() {
      File f = getSavePath();
      return f.getAbsolutePath() + "/cache.png";
  }

  public static Bitmap loadFromFile(String filename) {
      try {
          File f = new File(filename);
          if (!f.exists()) { return null; }
          Bitmap tmp = BitmapFactory.decodeFile(filename);
          return tmp;
      } catch (Exception e) {
          return null;
      }
  }
  public static Bitmap loadFromCacheFile() {
      return loadFromFile(getCacheFilename());
  }
  public static void saveToCacheFile(Bitmap bmp) {
      saveToFile(getCacheFilename(),bmp);
  }
  public static void saveToFile(String filename,Bitmap bmp) {
      try {
          FileOutputStream out = new FileOutputStream(filename);
          bmp.compress(CompressFormat.PNG, 100, out);
          out.flush();
          out.close();
      } catch(Exception e) {}
  }

  public static boolean hasSDCard() { // SD????????
      String status = Environment.getExternalStorageState();
      return status.equals(Environment.MEDIA_MOUNTED);
  }
  public static String getSDCardPath() {
      File path = Environment.getExternalStorageDirectory();
      return path.getAbsolutePath();
  }

}

 

 Now question comes,about the "Bitmap tmp = BitmapFactory.decodeFile(filename);",no matter how I modify it ,the result tmp is always null!
the main point is options,the options should be specifid,indicate the format of the image.So it should be like this:

BitmapFactory.Options opts = new Options();
opts.inPreferredConfig = Config.RGB_565;
tmp=BitmapFactory.decodeFile(bitmapPath,opts);

 

转载于:https://www.cnblogs.com/qiengo/archive/2012/06/19/2554572.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值