about 6 years ago

压缩图片

inSampleSize : 图片缩放值,1 表示宽度和高度不缩放,2 表示缩放原图宽度和高度的 1/2. 以此类推.

bm.compress(Bitmap.CompressFormat.JPEG, 80, output);

compress 方法的参数,Bitmap.CompressFormat.JPEG 表示压缩成JPEG格式,80 表示压缩图片的质量值,output 表示压缩的图片导入对象。

package com.yibu.kuaibu.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * Created by xufei on 4/17/15.
 */
public class ImageCompress {

    /**
     * 计算图片的缩放值
     *
     * @param options
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options,
                                            int rqsW, int rqsH) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
        if (rqsW == 0 || rqsH == 0) return 1;
        if (height > rqsH || width > rqsW) {
            final int heightRatio = Math.round((float) height/ (float) rqsH);
            final int widthRatio = Math.round((float) width / (float) rqsW);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     * 根据路径获得突破并压缩返回bitmap用于显示
     *
     * @return
     */
    public static Bitmap getSmallBitmap(String filePath, int width, int height) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, width, height);

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

        return BitmapFactory.decodeFile(filePath, options);
    }

    /**
     * compress
     *
     * @param filePath
     * @return
     */
    public static byte[] compressImageToByte(String filePath, int width, int height) {

        Bitmap bm = getSmallBitmap(filePath, width, height);

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 80, output); // 80 image quality

        return output.toByteArray();
    }

}

Resource

http://www.eoeandroid.com/thread-310706-1-1.html
http://www.360doc.com/content/14/0429/11/11800748_373154034.shtml
http://www.oschina.net/code/snippet_216465_36833

← ViewPager with FragmentPagerAdapter
 
comments powered by Disqus