android 图片压缩

在开发中图片压缩几乎是离不开的一个话题,下边是几种压缩的方法,有用到的可以自取。
//谷歌官方根据图片大小计算缩放因子

private void setPic() {
        // Get the dimensions of the View
        int targetW = imageView.getWidth();
        int targetH = imageView.getHeight();

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;

        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions);
        imageView.setImageBitmap(bitmap);
    }

//来自鲁班开源库

private fun compress(bitmap: Bitmap, path: String){
    var option = BitmapFactory.Options()
    option.inSampleSize = computeSize(bitmap.height,bitmap.width)
    var img = BitmapFactory.decodeFile(path, option)
    var fos = FileOutputStream(File(path))
    //把图片输出到本地文件
    img.compress(Bitmap.CompressFormat.JPEG,50,fos)
}

private fun computeSize(srcWidth:Int,srcHeight:Int): Int {	
    var srcWidth = if (srcWidth % 2 === 1) srcWidth + 1 else srcWidth
    var srcHeight = if (srcHeight % 2 === 1) srcHeight + 1 else srcHeight
    val longSide: Int = Math.max(srcWidth, srcHeight)
    val shortSide: Int = Math.min(srcWidth, srcHeight)
    val scale = shortSide.toFloat() / longSide
return if (scale <= 1 && scale > 0.5625) {
             if (longSide < 1664) {
                1
              } else if (longSide < 4990) {
                2
              } else if (longSide > 4990 && longSide < 10240) {
                4
              } else {
               if (longSide / 1280 == 0) 1 else longSide / 1280
              }
        } else if (scale <= 0.5625 && scale > 0.5) {
            if (longSide / 1280 == 0) 1 else longSide / 1280
                } else {
                Math.ceil(longSide / (1280.0 / scale)).toInt()
                }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值