bitmap和图片文件的转换


Bitmap对象保存为图片文件:
public static File saveBitMapToFile(Context context, String fileName, Bitmap bitmap, boolean isCover) {
   if(null == context || null == bitmap) {
      return null;
   }
   if(TextUtils.isEmpty(fileName)) {
      return null;
   }
   FileOutputStream fOut = null;
   try {
      File file = null;
      String fileDstPath = "";
      if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
         // 保存到sd卡
         fileDstPath = Environment.getExternalStorageDirectory().getAbsolutePath()
               + File.separator + "phonelive_bitmap" + File.separator + fileName;

         File homeDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
               + File.separator + "phonelive_bitmap" + File.separator);
         if (!homeDir.exists()) {
            homeDir.mkdirs();
         }
      } else {
         // 保存到file目录
         fileDstPath = context.getFilesDir().getAbsolutePath()
               + File.separator + "phonelive_bitmap" + File.separator + fileName;

         File homeDir = new File(context.getFilesDir().getAbsolutePath()
               + File.separator + "phonelive_bitmap" + File.separator);
         if (!homeDir.exists()) {
            homeDir.mkdir();
         }
      }

      file = new File(fileDstPath);

      if (!file.exists() || isCover) {
         // 简单起见,先删除老文件,不管它是否存在。
         file.delete();

         fOut = new FileOutputStream(file);
         if (fileName.endsWith(".jpg")) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fOut);
         } else {
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
         }
         fOut.flush();
         bitmap.recycle();
      }

      Log.i("FileSave", "saveDrawableToFile " + fileName
            + " success, save path is " + fileDstPath);
      return file;
   } catch (Exception e) {
      Log.e("FileSave", "saveDrawableToFile: " + fileName + " , error", e);
      return null;
   } finally {
      if(null != fOut) {
         try {
            fOut.close();
         } catch (Exception e) {
            Log.e("FileSave", "saveDrawableToFile, close error", e);
         }
      }
   }
}
图片文件转为Bitmap对象:
 
  

String filePath="c:/01.jpg"; Bitmap bitmap=BitmapFactory.decodeFile(filePath,getBitmapOption(2)); //将图片的长和宽缩小味原来的1/2 private Options getBitmapOption(int inSampleSize)

{         System.gc();         BitmapFactory.Options options = new BitmapFactory.Options();         options.inPurgeable = true;         options.inSampleSize = inSampleSize;         return options; }

你可能感兴趣的:(bitmap和图片文件的转换)