---
title: "Android 自定义camera压缩图片到指定大小"
author: "miaowei"
date: "2015-01-16T15:38:56Z"
tags: []
categories: ["移动开发"]
slug: "android-camera"
draft: false
lastmod: "2015-02-06T11:00:10Z"
id: 2176593
url: "https://technicalsearch.iteye.com/blog/2176593"
---

**Android 自定义camera-----当调用摄像头时，压缩图片到指定大小范围**

 

项目中的需求

**解决流程总结：**  
一、在调用摄像头时设置  
      //JPEG图像设置质量，这个基本可以解决大多少手机  
      Camera.Parameters.setJpegQuality(40);  
二、但是，有些手机还是不能使用第一种方法，则在上传图片时再次进行压缩处理  
    基本流程：  
    判断当前文件是否大于要压缩的大小（示例120），      //判断文件大小是否超过120K  
     if ((files*.getFile().length() / 1024) &gt; 120)*  
    *如果小于，直接上传图片*  
    *否则开始压缩：*  
    *1、将文件转换为byte数组*  
    *2、使用此方法进行压缩*  
        *public static byte\[] compressBitmap(byte\[] data, float size) {                /* 取得相片 \*/*  
        *Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);*  
        *//Bitmap bitmap = BitmapFactory.decodeFile(imageFile);*  
                *if (bitmap == null || getSizeOfBitmap(bitmap) &lt;= size) {*  
                        *return null;// 如果图片本身的大小已经小于指定大小，就没必要进行压缩*  
                *}*  
                *ByteArrayOutputStream baos = new ByteArrayOutputStream();*  
                *bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 如果签名是png的话，则不管quality是多少，都不会进行质量的压缩*  
                *int quality = 100;*  
                *while ((baos.toByteArray().length / 1024f) &gt; size) {*  
                        *quality -= 5;// 每次都减少5(如果这里-=10，有时候循环次数会提前结束)*  
                        *LogPrint.Print("console","------quality--------" + quality);*  
                        *baos.reset();// 重置baos即清空baos*  
                        *if (quality &lt;= 0) {*  
                                *break;*  
                        *}*  
                        *bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);*  
                        *LogPrint.Print("console","------质量--------" + baos.toByteArray().length / 1024f);*  
                *}*  
                *byte\[] byteData = baos.toByteArray();*  
                *return byteData;*  
        *}*  
          
        *private static long getSizeOfBitmap(Bitmap bitmap){*  
                  
                *ByteArrayOutputStream baos = new ByteArrayOutputStream();*  
            *bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//这里100的话表示不压缩质量*  
            *long length=baos.toByteArray().length/1024;//读出图片的kb大小*  
            *return length;*  
        *}*  
    *3、再将byte数组转换为文件file*  
    *4、开始上传*

*关于*[**Java文件与字节数组转换**](/blog/2174357)

 

以下方法进行图片压缩更有效

```
/**
	 * 根据图片路径进行压缩图片
	 * @param srcPath
	 * @return
	 */
	public static Bitmap getimage(String srcPath,int size) {  
        BitmapFactory.Options newOpts = new BitmapFactory.Options();  
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了,表示只返回宽高 
        newOpts.inJustDecodeBounds = true;  
        Bitmap bitmap = BitmapFactory.decodeFile(srcPath,newOpts);//此时返回bm为空  
          
        newOpts.inJustDecodeBounds = false;
        //当前图片宽高
        float w = newOpts.outWidth;  
        float h = newOpts.outHeight;  
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为  
        float hh = 800f;//这里设置高度为800f  
        float ww = 480f;//这里设置宽度为480f  
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可  
        int be = 1;//be=1表示不缩放  
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
        	LogPrint.Print("fileupload","------原始缩放比例 --------" + (newOpts.outWidth / ww));
            be = (int)(newOpts.outWidth / ww);
            //有时会出现be=3.2或5.2现象，如果不做处理压缩还会失败
            if ((newOpts.outWidth / ww) > be) {
				
            	be += 1;
			}
            //be = Math.round((float) newOpts.outWidth / (float) ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放  
        	LogPrint.Print("fileupload","------原始缩放比例 --------" + (newOpts.outHeight / hh));
            be = (int)(newOpts.outHeight / hh);
            if ((newOpts.outHeight / hh) > be) {
				
            	be += 1;
			}
        	//be = Math.round((float) newOpts.outHeight / (float) hh);
        }  
        if (be <= 0){
        	
        	be = 1; 
        }  
        newOpts.inSampleSize = be;//设置缩放比例  
        LogPrint.Print("fileupload","------设置缩放比例 --------" + newOpts.inSampleSize);
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了  
        bitmap = BitmapFactory.decodeFile(srcPath, newOpts);  
        return compressImage(bitmap,size);//压缩好比例大小后再进行质量压缩  
    } 
		
	/**
	 * 压缩图片
	 * @param image
	 * @param size
	 * @return
	 */
	private static Bitmap compressImage(Bitmap image,int size) {  
		  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中  
        int options = 100;  
        
        while ((baos.toByteArray().length / 1024) >= size) {  //循环判断如果压缩后图片是否大于等于size,大于等于继续压缩         
        	LogPrint.Print("fileupload","------ByteArray--------" + baos.toByteArray().length / 1024);
            baos.reset();//重置baos即清空baos  
            options -= 5;//每次都减少5 
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中  
            LogPrint.Print("fileupload","------压缩质量--------" + options);
        }  
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中  
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片  
        return bitmap;  
    } 
	
	/**
	 * Bitmap转byte数组
	 * @param bitmap
	 * @return
	 */
	public static byte[] compressBitmap(Bitmap bitmap) {
		if (bitmap == null ) {
			return null;//		
             }
		/* 取得相片 */
        Bitmap tempBitmap = bitmap;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		tempBitmap.compress(Bitmap.CompressFormat.JPEG, 70, baos);// 如果签名是png的话，则不管quality是多少，都不会进行质量的压缩
		byte[] byteData = baos.toByteArray();
		return byteData;
	}
```