图片压缩算法,3M压缩到200K

MainActivity:
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.example.yasuo;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
 
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
 
public class MainActivity extends Activity {
 
        final String PATH = Environment.getExternalStorageDirectory()
                        + "/Bst/a.jpg" ;
 
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super .onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                init();
        }
 
        private void init() {
                try {
                        getThumbUploadPath(PATH, 480 );
                } catch (Exception e) {
                        Log.e( "eeee" , e.toString());
                }
        }
 
        private String getThumbUploadPath(String oldPath, int bitmapMaxWidth) throws Exception {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true ;
                BitmapFactory.decodeFile(oldPath, options);
                int height = options.outHeight;
                int width = options.outWidth;
                int reqHeight = 0 ;
                int reqWidth = bitmapMaxWidth;
                reqHeight = (reqWidth * height)/width;
                // 在内存中创建bitmap对象,这个对象按照缩放大小创建的
                options.inSampleSize = calculateInSampleSize(options, bitmapMaxWidth, reqHeight);
//                System.out.println("calculateInSampleSize(options, 480, 800);==="
//                                + calculateInSampleSize(options, 480, 800));
                options.inJustDecodeBounds = false ;
                Bitmap bitmap = BitmapFactory.decodeFile(oldPath, options);
                //Log.e("asdasdas", "reqWidth->"+reqWidth+"---reqHeight->"+reqHeight);
                Bitmap bbb = compressImage(Bitmap.createScaledBitmap(bitmap, bitmapMaxWidth, reqHeight, false ));
                String timeStamp = new SimpleDateFormat( "yyyyMMdd_HHmmss" )
                                .format( new Date());
                return BitmapUtils.saveImg(bbb, MD5Utils.md5(timeStamp));
        }
 
        private int calculateInSampleSize(BitmapFactory.Options options,
                        int reqWidth, int reqHeight) {
                // Raw height and width of image
                final int height = options.outHeight;
                final int width = options.outWidth;
                int inSampleSize = 1 ;
 
                if (height > reqHeight || width > reqWidth) {
                        if (width > height) {
                                inSampleSize = Math.round(( float ) height / ( float ) reqHeight);
                        } else {
                                inSampleSize = Math.round(( float ) width / ( float ) reqWidth);
                        }
                }
                return inSampleSize;
        }
 
        private Bitmap compressImage(Bitmap image) {
 
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 80 , baos); // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
                int options = 100 ;
                while (baos.toByteArray().length / 1024 > 100 ) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
                        options -= 10 ; // 每次都减少10
                        baos.reset(); // 重置baos即清空baos
                        image.compress(Bitmap.CompressFormat.JPEG, options, baos); // 这里压缩options%,把压缩后的数据存放到baos中
                }
                ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); // 把压缩后的数据baos存放到ByteArrayInputStream中
                Bitmap bitmap = BitmapFactory.decodeStream(isBm, null , null ); // 把ByteArrayInputStream数据生成图片
                return bitmap;
        }
 
}







BitmapUtils:
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.example.yasuo;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
 
import android.graphics.Bitmap;
import android.os.Environment;
 
/**
  * 将bitmap保存在SD卡
  * @author xinruzhou
  *
  */
public class BitmapUtils {
 
        /**
          *
          * @param b Bitmap
          * <a href="\"http://www.eoeandroid.com/home.php?mod=space&uid=7300\"" target="\"_blank\"">@return</a> 图片存储的位置
          * @throws FileNotFoundException
          */
        public static String saveImg(Bitmap b,String name) throws Exception{
                String path = Environment.getExternalStorageDirectory().getPath()+File.separator+ "test/headImg/" ;
                File mediaFile = new File(path + File.separator + name + ".jpg" );
                if (mediaFile.exists()){
                        mediaFile.delete();
                         
                }
                if (! new File(path).exists()){
                        new File(path).mkdirs();
                }
                mediaFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(mediaFile);
                b.compress(Bitmap.CompressFormat.PNG, 100 , fos);
                fos.flush();
                fos.close();
                b.recycle();
                b = null ;
                System.gc();
                return mediaFile.getPath();
        }
}






MD5Utils:
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.example.yasuo;
 
import java.security.MessageDigest;
 
public class MD5Utils {
 
        /**
          * MD5加密
          * @param str 要加密的字符串
          * @return 加密后的字符串
          */
        public static String md5(String str) {
                MessageDigest md5 = null ;
                try {
                        md5 = MessageDigest.getInstance( "MD5" );
                } catch (Exception e) {
                        e.printStackTrace();
                        return "" ;
                }
                char [] charArray = str.toCharArray();
                byte [] byteArray = new byte [charArray.length];
                for ( int i = 0 ; i < charArray.length; i++) {
                        byteArray<i> = ( byte ) charArray<i>;
                }
                byte [] md5Bytes = md5.digest(byteArray);
                StringBuffer hexValue = new StringBuffer();
                for ( int i = 0 ; i < md5Bytes.length; i++) {
                        int val = (( int ) md5Bytes<i>) & 0xff ;
                        if (val < 16 ) {
                                hexValue.append( "0" );
                        }
                        hexValue.append(Integer.toHexString(val));
                }
                return hexValue.toString();
        }
}
</i></i></i>

就这么多~

转自:http://www.eoeandroid.com/thread-310706-1-1.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值