图片压缩

这篇文章主要介绍了Android中几种图片压缩处理方法,本文讲解了质量压缩方法、获得缩略图、图片缩放三种方法并分别给出示例代码,需要的朋友可以参考下(都是从网上摘的)

  Android中图片的存在形式:

  1:文件形式:二进制形式存在与硬盘中。

  2:流的形式:二进制形式存在与内存中。

  3:Bitmap的形式

  三种形式的区别:

  文件形式和流的形式:对图片体积大小并没有影响。也就是说,如果你手机SD卡上的图片通过流的形式读到内存中,在内存中的大小也是原图的大小。

  注意:不是Bitmap的形式。

  Bitmap的形式:图片占用的内存会瞬间变大。

  以下是代码的形式:

  ?

1
2
3
4
5
6
7
8
9
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
90
91
92
93
94
/**
* 图片压缩的方法总结
*/
 
/*
* 图片压缩的方法01:质量压缩方法
*/
private Bitmap compressImage(Bitmap beforBitmap) {
 
// 可以捕获内存缓冲区的数据,转换成字节数组。
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (beforBitmap != null) {
// 第一个参数:图片压缩的格式;第二个参数:压缩的比率;第三个参数:压缩的数据存放到bos中
beforBitmap.compress(CompressFormat.JPEG, 100, bos);
int options = 100;
// 循环判断压缩后的图片是否是大于100kb,如果大于,就继续压缩,否则就不压缩
while (bos.toByteArray().length / 1024 > 100) {
bos.reset();// 置为空
// 压缩options%
beforBitmap.compress(CompressFormat.JPEG, options, bos);
// 每次都减少10
options -= 10;
 
}
// 从bos中将数据读出来 存放到ByteArrayInputStream中
ByteArrayInputStream bis = new ByteArrayInputStream(
bos.toByteArray());
// 将数据转换成图片
Bitmap afterBitmap = BitmapFactory.decodeStream(bis);
return afterBitmap;
}
return null;
}
 
/*
* 图片压缩方法02:获得缩略图
*/
public Bitmap getThumbnail(int id) {
// 获得原图
Bitmap beforeBitmap = BitmapFactory.decodeResource(
mContext.getResources(), id);
// 宽
int w = mContext.getResources()
.getDimensionPixelOffset(R.dimen.image_w);
// 高
int h = mContext.getResources().getDimensionPixelSize(R.dimen.image_h);
 
// 获得缩略图
Bitmap afterBitmap = ThumbnailUtils
.extractThumbnail(beforeBitmap, w, h);
return afterBitmap;
 
}
 
/**
* 图片压缩03
*
* @param id
* 要操作的图片的大小
* @param newWidth
* 图片指定的宽度
* @param newHeight
* 图片指定的高度
* @return
*/
public Bitmap compressBitmap(int id, double newWidth, double newHeight) {
// 获得原图
Bitmap beforeBitmap = BitmapFactory.decodeResource(
mContext.getResources(), id);
// 图片原有的宽度和高度
float beforeWidth = beforeBitmap.getWidth();
float beforeHeight = beforeBitmap.getHeight();
 
// 计算宽高缩放率
float scaleWidth = 0;
float scaleHeight = 0;
if (beforeWidth > beforeHeight) {
scaleWidth = ((float) newWidth) / beforeWidth;
scaleHeight = ((float) newHeight) / beforeHeight;
} else {
scaleWidth = ((float) newWidth) / beforeHeight;
scaleHeight = ((float) newHeight) / beforeWidth;
}
 
// 矩阵对象
Matrix matrix = new Matrix();
// 缩放图片动作 缩放比例
matrix.postScale(scaleWidth, scaleHeight);
// 创建一个新的Bitmap 从原始图像剪切图像
Bitmap afterBitmap = Bitmap.createBitmap(beforeBitmap, 0, 0,
(int) beforeWidth, (int) beforeHeight, matrix, true);
return afterBitmap;
 
}
第四种

public static Bitmap revitionImageSize(String path) throws IOException {
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                                new File(path)));
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(in, null, options);
                in.close();
                int i = 0;
                Bitmap bitmap = null;
                while (true) {
                        if ((options.outWidth >> i <= 1000)
                                        && (options.outHeight >> i <= 1000)) {
                                in = new BufferedInputStream(
                                                new FileInputStream(new File(path)));
                                options.inSampleSize = (int) Math.pow(2.0D, i);
                                options.inJustDecodeBounds = false;
                                bitmap = BitmapFactory.decodeStream(in, null, options);
                                break;
                        }
                        i += 1;
                }
                return bitmap;
        }

第五种

 MainActivity:
[mw_shl_code=java,true]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;
        }

}
[/mw_shl_code]







BitmapUtils:
[mw_shl_code=java,true]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
         * @return 图片存储的位置
         * @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();
        }
}
[/mw_shl_code]





MD5Utils:
[mw_shl_code=java,true]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 = (byte) charArray;
                }
                byte[] md5Bytes = md5.digest(byteArray);
                StringBuffer hexValue = new StringBuffer();
                for (int i = 0; i < md5Bytes.length; i++) {
                        int val = ((int) md5Bytes) & 0xff;
                        if (val < 16) {
                                hexValue.append("0");
                        }
                        hexValue.append(Integer.toHexString(val));
                }
                return hexValue.toString();
        }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值