android图片压缩不失真实战

      相信大家在项目开发中,不管是大小企业,服务器上传速度都是有限的,更何况不少公司是通过存在第三方的云存储如七牛中间站的,这就造成假设我们需要上传多张图片会很慢,给用户很差的体验了,这里是个人在项目中需求需要上传三十张照片,对图片压缩的心得,可能存在不足的地方,希望能指正。

废话客套话就不多说了,我们搬砖装修吧,核心实现代码如下:

// 根据路径获得图片并压缩,返回bitmap用于显示

public static Bitmap getSmallBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(filePath, options);
    }
//把bitmap转换成String
public static String bitmapToString(String filePath) {

        Bitmap bm = getSmallBitmap(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }
另外在我们存储图片还可以使用Base64转化为字节流保存文件,文件传输入,为了传输方便最好的办法是将文件转化成base64字串,再将base64字串转成字节流保存在文件了。不过这种做法虽然简单,但还要根据实际需求进行选择,弊端是不能转太大的文件,文件太大会造成效率问题,现在暂且这么处理。
具体代码如下:
 
public void saveBitmap(String filePath) {

        try {
            String path = Environment.getExternalStorageDirectory() + "/test" + System.currentTimeMillis() + ".png";
            decoderBase64File(bitmapToString(filePath), path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * decoderBase64File:(将base64字符解码保存文件). <br/>
     *
     * @param base64Code 编码后的字串
     * @param savePath   文件保存路径
     * @throws Exception
     * @author BinaryKnight
     * @since JDK 1.6
     */
    public void decoderBase64File(String base64Code, String savePath) throws Exception {
//byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        byte[] buffer = Base64.decode(base64Code, Base64.DEFAULT);
        File f = new File(savePath);
        f.createNewFile();
        FileOutputStream out = new FileOutputStream(f);
        out.write(buffer);
        out.close();
    }

 
 
对图片压缩的讲解:压缩图片我们需要知道图片的尺寸,然后根据比例无损压缩:
主要分成以下三步:
1.获取原始图片的长和宽
	BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        int height = options.outHeight;
        int width = options.outWidth; 
以上代码是对图片进行解码,inJustDecodeBounds设置为true,可以不把图片读到内存中,但依然可以计算出图片的大小,这正好可以满足我们第一步的需要
2.计算压缩比例	
  int height = options.outHeight;
     int width = options.outWidth; 
     int inSampleSize = 1;
     int reqHeight=800;
     int reqWidth=480;
     if (height > reqHeight || width > reqWidth) {
    final int heightRatio = Math.round((float) height/ (float) reqHeight);
    final int widthRatio = Math.round((float) width / (float) reqWidth);            
    inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
     }
这里以手机分辨率480*800为例,我们期望的宽高分别设定为480,800,这两个值只是我们的期望值,实际压缩后的宽度和高度都会比期望的要大。如果原始图片的尺寸大于我们设定的期望值才会进行压缩,否则不压缩。heightRatio是图片原始高度与压缩后高度的倍数,widthRatio是图片原始宽度与压缩后宽度的倍数。inSampleSize为heightRatio与widthRatio中最小的那个,inSampleSize就是缩放值。 inSampleSize为1表示宽度和高度不缩放,为2表示压缩后的宽度与高度为原来的1/2。
3.缩放并压缩图片
//在内存中创建bitmap对象,这个对象按照缩放大小创建的
        byte[] b = baos.toByteArray();options.inSampleSize = calculateInSampleSize(options, 480, 800);
 	options.inJustDecodeBounds = false;
        Bitmap bitmap= BitmapFactory.decodeFile(filePath, options);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 60, baos);
        byte[] b = baos.toByteArray();
前三行的代码其实已经得到了一个缩放的bitmap对象,如果你在应用中显示图片,就可以使用这个bitmap对象了。由于考虑到网络流量的问题。我们好需要牺牲图片的质量来换取一部分空间,这里调用bm.compress()方法进行压缩,这个方法的第二个参数,如果是100,表示不压缩,我这里设置的是60,你也可以更加你的需要进行设置,在实验的过程中我设置为30,图片都不会失真。
压缩效果:可以把1.5M左右的图片压缩到100K左右,并且没有失真。			
另外附加干货:
/*
压缩图片,处理某些手机拍照角度旋转的问题
*/
public static String compressImage(Context context,String filePath,String fileName,int q) throws FileNotFoundException {

        Bitmap bm = getSmallBitmap(filePath);

        int degree = readPictureDegree(filePath);

        if(degree!=0){//旋转照片角度
            bm=rotateBitmap(bm,degree);
        }

        File imageDir = SDCardUtils.getImageDir(context);

        File outputFile=new File(imageDir,fileName);

        FileOutputStream out = new FileOutputStream(outputFile);

        bm.compress(Bitmap.CompressFormat.JPEG, q, out);

        return outputFile.getPath();
    }
判断照片角度
public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                degree = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                degree = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                degree = 270;
                break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }
旋转照片
public static Bitmap rotateBitmap(Bitmap bitmap,int degress) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            m.postRotate(degress); 
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), m, true);
            return bitmap;
        }
        return bitmap;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值