[Android] 压缩图片并保存

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

原文地址请保留http://www.cnblogs.com/rossoneri/p/3995096.html 

先加权限

1 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

 

 1 private void saveCroppedImage(Bitmap bmp) {
 2         File file = new File("/sdcard/myFolder");
 3         if (!file.exists())
 4             file.mkdir();
 5 
 6         file = new File("/sdcard/temp.jpg".trim());
 7         String fileName = file.getName();
 8         String mName = fileName.substring(0, fileName.lastIndexOf("."));
 9         String sName = fileName.substring(fileName.lastIndexOf("."));
10 
11         // /sdcard/myFolder/temp_cropped.jpg
12         String newFilePath = "/sdcard/myFolder" + "/" + mName + "_cropped" + sName;
13         file = new File(newFilePath);
14         try {
15             file.createNewFile();
16             FileOutputStream fos = new FileOutputStream(file);
17             bmp.compress(CompressFormat.JPEG, 50, fos);
18             fos.flush();
19             fos.close();
20         } catch (IOException e) {
21             // TODO Auto-generated catch block
22             e.printStackTrace();
23         }
24 
25     }

 这里比较重要的方法就是

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

文档如下:

boolean android.graphics.Bitmap.compress(CompressFormat format, int quality, OutputStream stream)

 

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:

format The format of the compressed image

quality Hint 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

stream The outputstream to write the compressed data.

Returns:

true if successfully compressed to the specified stream.

 

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

 1 /**
 2      * Specifies the known formats a bitmap can be compressed into
 3      */
 4     public enum CompressFormat {
 5         JPEG    (0),
 6         PNG     (1),
 7         WEBP    (2);
 8 
 9         CompressFormat(int nativeInt) {
10             this.nativeInt = nativeInt;
11         }
12         final int nativeInt;
13     }

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

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

附上几个链接:

android bitmap compress(图片压缩)

Android中文API(136) —— Bitmap

 

转载于:https://www.cnblogs.com/rossoneri/p/3995096.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值