大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > Android技巧 > android保存bitmap到指定路径

android保存bitmap到指定路径

关键词:androidbitmap指定路径保存  阅读(20247) 赞(14)

[摘要]本文是对android保存bitmap到指定路径的讲解,对学习Android编程技术有所帮助,与大家分享。

不难,但用的时候有时候突然会想不起来。。记录一下吧

先加权限

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 private void saveCroppedImage(Bitmap bmp) {
         File file = new File("/sdcard/myFolder");
         if (!file.exists())
             file.mkdir();
 
         file = new File("/sdcard/temp.jpg".trim());
         String fileName = file.getName();
         String mName = fileName.substring(0, fileName.lastIndexOf("."));
         String sName = fileName.substring(fileName.lastIndexOf("."));
 
         // /sdcard/myFolder/temp_cropped.jpg
         String newFilePath = "/sdcard/myFolder" + "/" + mName + "_cropped" + sName;
         file = new File(newFilePath);
         try {
             file.createNewFile();
             FileOutputStream fos = new FileOutputStream(file);
             bmp.compress(CompressFormat.JPEG, 50, fos);
             fos.flush();
             fos.close();
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
 
     }

这里比较重要的方法就是

bmp.compress(CompressFormat.JPEG, 50, fos);

文档如下:

booleanandroid.graphics.Bitmap.compress(CompressFormatformat,int quality,OutputStreamstream)

Write a compressed version of the bitmap to the specified outputstream. If this returns true, the bitmap can be reconstructed by passing a corresponding inputstream to BitmapFactory.decodeStream(). Note: not all Formats support all bitmap configs directly, so it is possible that the returned bitmap from BitmapFactory could be in a different bitdepth, and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque pixels).

Parameters:

formatThe format of the compressed image

qualityHint to the compressor, 0-100. 0 meaning compress for small size, 100 meaning compress for max quality. Some formats, like PNG which is lossless, will ignore the quality setting

streamThe outputstream to write the compressed data.

Returns:

true if successfully compressed to the specified stream.

第一个参数有三种,源码如下

 /**
      * Specifies the known formats a bitmap can be compressed into
      */
     public enum CompressFormat {
         JPEG    (0),
         PNG     (1),
         WEBP    (2);
 
         CompressFormat(int nativeInt) {
             this.nativeInt = nativeInt;
         }
         final int nativeInt;
     }

因为转换的原始bitmap后缀有不同,比如我用的jpg文件,保存下来也是jpg文件。但用的是CompressFormat.JPEG做参数。

这个参数应该和原始文件类型有关,这是个知识点,日后研究研究,写个根据类型自动选择参数的方法。

附上几个链接:

android bitmap compress(图片压缩)

Android中文API(136) —— Bitmap



相关评论