29 图片缩小案例

当一张图片如果像素过大的在安卓原比例展示将直接内存溢出
也许一张图片大小可能也就几百kb 但是在安卓中不是这样计算

假设 一张1024*1920的图片

  • 那么假设他是256色图 那么每个像素点要存储256个颜色值那么需要2^8位正好是一个字节
  • 那么在安卓设备显示需要 1024*1920 *1= 1.875mb
    • 然后我们jpeg图片完全不止256色 如果高品质每像素点25k
    • 1024*1920 *25 = 46mb
  • 显然这是不能接受的所以们需要约束比例显示
package com.qf.sxy.imagescale;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {

    private ImageView iv;

    private Bitmap resourseBitmap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv = ((ImageView) findViewById(R.id.iv_get));

        //获取图片
        resourseBitmap  = BitmapFactory.decodeResource(getResources(),R.mipmap.v5);
        iv.setImageBitmap(resourseBitmap);
    }
    //按钮点击事件 点击缩放图片
    public void MyClick(View view) {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //质量压缩
        resourseBitmap.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
        //获取byte{}
        byte[] bytes = outputStream.toByteArray();
        Bitmap bitmap = getImageScale(bytes,100,100);
        //iv 是布局中一个控件
        iv.setImageBitmap(bitmap);
    }

    //进行二次采样
    private Bitmap getImageScale(byte[] bytes,int newWidth ,int newHeight) {

        //图片的配置
        BitmapFactory.Options options = new BitmapFactory.Options();
        //仅仅解码图片的边缘部分
        options.inJustDecodeBounds = true;
        //将解析结果放入字节数组
        // 如果options.inJustDecodeBounds = true;那么返回bitmap是null
        BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
        //获取原始的宽高
        int outWidth = options.outWidth;
        int outHeight = options.outHeight;

        int scaleWidth = outWidth/newWidth;
        int scaleHeight = outHeight/newHeight;

        //获取缩放的值 值越大图片越小 我们只取最大缩放倍数
        // 原因: 如果宽要缩小 2 倍  高缩小3倍  你为2倍时因为高没有达到比列可能会看不见或者依然内存溢出
        int scale = scaleWidth>scaleHeight?scaleWidth:scaleHeight;
        //设置缩放比例
        //这里注意 约束比例只能是2^n方 也就是1 2 4 8 16
        //举个例子
        // 列子 1:如果你scale 为 3 那么将缩放比列为2
        // 例子 2:如果你scale 为 5 那么缩放比例为 4
        // 也就是说不到缩放比列不到2^n的 那么缩小倍数为 2^(n-1)方
        // 例子 3 : 如果你scale 为 5 因为 5小于 2^3 那么缩小倍数为2^(3-1)方 也就是4倍
        options.inSampleSize =scale;
        // 关闭只解析边缘 不然返回null
        options.inJustDecodeBounds = false;

        Bitmap bitmap =   BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);

        return bitmap;
    }
}
原文地址:https://www.cnblogs.com/muyuge/p/6152160.html