图片压缩的常用方法帮助类

本文分享了一个项目中常用的图片处理类,包含图片等比例缩放、正方形居中裁剪等功能,适用于需要进行图片处理的开发场景。

这是我做项目使用图片压缩最常用的类,现在分享出来给大家。

/**
 * Created by Administrator on 2015/1/22 0022.
 */
public class ImageUtils {
    /**
     * 图片等比例缩放
     * @param b
     * @param x
     * @param y
     * @return
     */
    public static Bitmap getBitMap(Bitmap b,float x,float y){
        int w=b.getWidth();
        int h=b.getHeight();
        float sx=x/w;//图片缩放比例
        float sy=y/h;
        Matrix matrix = new Matrix();
        matrix.postScale(sx, sy); // 设置缩放比例
        Bitmap resizeBmp = Bitmap.createBitmap(b, 0, 0, w,
                h, matrix, true);
        return resizeBmp;
    }
    /**
     * 正方形居中切法
     * @param b 原图bitmap
     * @return
     */
    public static Bitmap getBitMap(Bitmap b){
        int oldwidth = b.getWidth();
        int oldheight = b.getHeight();
        int newwidth = 0;
        int newheight = 0;
        int newx = 0;
        int newy = 0;
        if(oldwidth == oldheight){
            newwidth = oldwidth;
            newheight = oldwidth;
        }else if(oldwidth > oldheight){
            newx = (oldwidth - oldheight) / 2;
            newheight = oldheight;
            newwidth = oldheight;
        }else if(oldwidth < oldheight){
            newy = (oldheight - oldwidth) / 2;
            newheight = oldwidth;
            newwidth = oldwidth;
        }else{
            newwidth = oldwidth;
            newheight = oldheight;
        }
        Bitmap bitmap = Bitmap.createBitmap(b,newx,newy,newwidth,newheight);
        return bitmap;
    }

    public static int getWidthForPhone(WindowManager wm){
        DisplayMetrics DM = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(DM);
        return DM.widthPixels;
    }
    public static int getHeightForPhone(WindowManager wm){
        DisplayMetrics DM = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(DM);
        return DM.heightPixels;
    }

    public static Bitmap setImagePostion(WindowManager wm,Resources res,int imgId){
        int windowWidth = getWidthForPhone(wm);
        Bitmap bitmap = BitmapFactory.decodeResource(res, imgId);
        int height = bitmap.getHeight() * windowWidth / bitmap.getWidth();
        Bitmap bm = ImageUtils.getBitMap(bitmap, windowWidth, height);
        return bm;
    }

    public static Bitmap setImagePostion(WindowManager wm,Bitmap bitmap){
        int windowWidth = getWidthForPhone(wm);
        int height = bitmap.getHeight() * windowWidth / bitmap.getWidth();
        Bitmap bm = ImageUtils.getBitMap(bitmap, windowWidth, height);
        return  bm;
    }



}

技术源于分享!!!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值