bitmap的一些工具

1.100*100圓形頭像;當然也可以直接在網上找圓形的imageview;

public static void getCropped2Bitmap(Bitmap bmp, ImageView iv) {
    int radius = 50;
    Bitmap scaledSrcBmp;
    int diameter = radius * 2;
    if (bmp.getWidth() != diameter || bmp.getHeight() != diameter)
        scaledSrcBmp = Bitmap.createScaledBitmap(bmp, diameter, diameter, false);
    else
        scaledSrcBmp = bmp;
    Bitmap output = Bitmap.createBitmap(scaledSrcBmp.getWidth(), scaledSrcBmp.getHeight(), Config.ARGB_4444);
    Canvas canvas = new Canvas(output);

    final Paint paint = new Paint();
    final Rect rect = new Rect(0, 0, scaledSrcBmp.getWidth(), scaledSrcBmp.getHeight());

    paint.setAntiAlias(true);
    paint.setFilterBitmap(true);
    paint.setDither(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(Color.parseColor("#BAB399"));
    canvas.drawCircle(scaledSrcBmp.getWidth() / 2, scaledSrcBmp.getHeight() / 2, scaledSrcBmp.getWidth() / 2,
            paint);
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
    canvas.drawBitmap(scaledSrcBmp, rect, rect, paint);
    iv.setImageBitmap(compressImage(output));
}

2.bitmap轉字節

public static byte[] Bitmap2Bytes(Bitmap bm) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    return baos.toByteArray();
}

3.在使用引導頁或者歡迎頁的大圖的時候,最好是壓縮一下;

public static Bitmap readBitMap(Context context, int resId) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inPreferredConfig = Config.RGB_565;
    opt.inPurgeable = true;
    opt.inInputShareable = true;
    // 獲取資源圖片
    InputStream is = context.getResources().openRawResource(resId);
    return BitmapFactory.decodeStream(is, null, opt);
}

質量壓縮

public static Bitmap compressImage(Bitmap image) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 30, baos);// 質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中
    int options = 100;
    while (baos.toByteArray().length / 1024 > 100) { // 循環判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮
        baos.reset();// 重置baos即清空baos
        image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 這裏壓縮options%,把壓縮後的數據存放到baos中
        options -= 10;// 每次都減少10
    }
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把壓縮後的數據baos存放到ByteArrayInputStream中
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream數據生成圖片
    return bitmap;
}


以上是最近項目中用到的bitmap工具,在此以作記錄






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章