溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android BitmapUtils工具類使用詳解

發(fā)布時(shí)間:2020-10-06 07:30:48 來源:腳本之家 閱讀:290 作者:xi陽 欄目:移動(dòng)開發(fā)

本文實(shí)例為大家分享了Android BitmapUtils工具類的具體代碼,供大家參考,具體內(nèi)容如下

public final class BitmapUtils {
  public static final String TAG = "BitmapUtil";
  private static int sShotScreenWidth = 480;
  private static int sShotScreenHeight = 720;
  private static int sShotScreenSize = sShotScreenWidth * sShotScreenHeight;

  @SuppressLint("StaticFieldLeak")
  private static Context mContext;
  @SuppressLint("StaticFieldLeak")
  private static Activity mActivity;

  public void init(Context context,Activity ac) {
    mContext=context;
    mActivity=ac;

    DisplayMetrics dm = new DisplayMetrics();
    ac.getWindowManager().getDefaultDisplay().getMetrics(dm);
    //獲取屏幕分辨率
    sShotScreenWidth = dm.widthPixels;
    sShotScreenHeight = dm.heightPixels;
    sShotScreenSize = sShotScreenWidth * sShotScreenHeight;
  }

  /**
   * 圖片合成
   * 
   * @param bitmap 位圖1
   * @param mark 位圖2
   * @return Bitmap
   */
  public static Bitmap createBitmap(Bitmap bitmap, Bitmap mark) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();
    int mW = mark.getWidth();
    int mH = mark.getHeight();
    Bitmap newbitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 創(chuàng)建一個(gè)長寬一樣的位圖

    Canvas cv = new Canvas(newbitmap);
    cv.drawBitmap(bitmap, 0, 0, null);// 在 0,0坐標(biāo)開始畫入bitmap
    cv.drawBitmap(mark, w - mW , h - mH , null);// 在右下角畫入水印mark
    cv.save(Canvas.ALL_SAVE_FLAG);// 保存
    cv.restore();// 存儲
    return newbitmap;
  }

  /**
   * 放大縮小圖片
   * @param bitmap 位圖
   * @param w 新的寬度
   * @param h 新的高度
   * @return Bitmap
   */
  public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    Matrix matrix = new Matrix();
    float scaleWidht = ((float) w / width);
    float scaleHeight = ((float) h / height);
    matrix.postScale(scaleWidht, scaleHeight);
    return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
  }

  /**
   * 旋轉(zhuǎn)圖片
   * @param bitmap 要旋轉(zhuǎn)的圖片
   * @param angle 旋轉(zhuǎn)角度
   * @return bitmap
   */
  public static Bitmap rotate(Bitmap bitmap,int angle) {
    Matrix matrix = new Matrix();
    matrix.postRotate(angle);
    return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
        bitmap.getHeight(), matrix, true);
  }

  /**
   * 圓形圖片
   *@param source 位圖
   * @param strokeWidth 裁剪范圍 0表示最大
   * @param bl 是否需要描邊
   * @param bl 畫筆粗細(xì)
   * @param bl 顏色代碼
   * @return bitmap
   */
  public static Bitmap createCircleBitmap(Bitmap source, int strokeWidth, boolean bl,int edge,int color) {

    int diameter = source.getWidth() < source.getHeight() ? source.getWidth() : source.getHeight();
    Bitmap target = Bitmap.createBitmap(diameter, diameter, Config.ARGB_8888);
    Canvas canvas = new Canvas(target);//創(chuàng)建畫布

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    canvas.drawCircle(diameter / 2, diameter / 2, diameter / 2, paint);//繪制圓形
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));//取相交裁剪
    canvas.drawBitmap(source, strokeWidth, strokeWidth, paint);
    if(bl) {
      if (color == 0) color = 0xFFFEA248;//默認(rèn)橘黃色
      paint.setColor(color);
      paint.setStyle(Paint.Style.STROKE);//描邊
      paint.setStrokeWidth(edge);
      canvas.drawCircle(diameter / 2, diameter / 2, diameter / 2, paint);
    }
    return target;
  }

  /**
   * 圓角圖片
   * @param bitmap 位圖
   * @param rx x方向上的圓角半徑
   * @param ry y方向上的圓角半徑
   * @param bl 是否需要描邊
   * @param bl 畫筆粗細(xì)
   * @param bl 顏色代碼
   * @return bitmap
   */
  public static Bitmap createCornerBitmap(Bitmap bitmap,int rx,int ry,boolean bl,int edge,int color) {
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(output);//創(chuàng)建畫布

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
    RectF rectF = new RectF(rect);
    canvas.drawRoundRect(rectF, rx, ry, paint);//繪制圓角矩形
    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));//取相交裁剪
    canvas.drawBitmap(bitmap, rect, rect, paint);
    if(bl) {
      if (color == 0) color = 0xFFFEA248;//默認(rèn)橘黃色
      paint.setColor(color);
      paint.setColor(color);
      paint.setStyle(Paint.Style.STROKE);//描邊
      paint.setStrokeWidth(edge);
      canvas.drawRoundRect(rectF, rx, ry, paint);
    }
    return output;
  }

  /**
   * 按比例裁剪圖片
   * @param bitmap 位圖
   * @param wScale 裁剪寬 0~100%
   * @param hScale 裁剪高 0~100%
   * @return bitmap
   */
  public static Bitmap cropBitmap(Bitmap bitmap, float wScale, float hScale) {
    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int wh = (int) (w * wScale);
    int hw = (int) (h * hScale);

    int retX = (int) (w * (1 - wScale) / 2);
    int retY = (int) (h * (1 - hScale) / 2);

    return Bitmap.createBitmap(bitmap, retX, retY, wh, hw, null, false);
  }

  /**
   * 獲得帶倒影的圖片方法
   * @param bitmap 位圖
   * @param region 倒影區(qū)域 0.1~1
   * @return bitmap
   */
  public static Bitmap createReflectionBitmap(Bitmap bitmap,float region) {

    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    Matrix matrix = new Matrix();
    matrix.preScale(1, -1);//鏡像縮放
    Bitmap reflectionBitmap = Bitmap.createBitmap(
                         bitmap,0
                        , (int)(height*(1-region))//從哪個(gè)點(diǎn)開始繪制
                        , width
                        ,(int) (height*region)//繪制多高
                        , matrix, false);

    Bitmap reflectionWithBitmap = Bitmap.createBitmap(width,height+ (int) (height*region),
                              Config.ARGB_8888);
    Canvas canvas = new Canvas(reflectionWithBitmap);
    canvas.drawBitmap(bitmap, 0, 0, null);
    canvas.drawBitmap(reflectionBitmap, 0, height , null);

    LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
                        reflectionWithBitmap.getHeight()
                        , 0x70ffffff, 0x00ffffff, TileMode.CLAMP);

    Paint paint = new Paint();
    paint.setShader(shader);
    paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));//取兩層繪制交集。顯示下層。
    canvas.drawRect(0, height, width, reflectionWithBitmap.getHeight() , paint);
    return reflectionWithBitmap;
  }

  /**
   * 圖片質(zhì)量壓縮
   * @param bitmap
   * @param many 百分比
   * @return
   */
  public static Bitmap compressBitmap(Bitmap bitmap, float many){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, (int)many*100, baos);
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
    return BitmapFactory.decodeStream(isBm, null, null);
  }

  /**
   * 高級圖片質(zhì)量壓縮
   *@param bitmap 位圖
   * @param maxSize 壓縮后的大小,單位kb
   */
  public static Bitmap imageZoom(Bitmap bitmap, double maxSize) {
    // 將bitmap放至數(shù)組中,意在獲得bitmap的大小(與實(shí)際讀取的原文件要大)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // 格式、質(zhì)量、輸出流
    bitmap.compress(Bitmap.CompressFormat.PNG, 70, baos);
    byte[] b = baos.toByteArray();
    // 將字節(jié)換成KB
    double mid = b.length / 1024;
    // 獲取bitmap大小 是允許最大大小的多少倍
    double i = mid / maxSize;
    // 判斷bitmap占用空間是否大于允許最大空間 如果大于則壓縮 小于則不壓縮
    doRecycledIfNot(bitmap);
    if (i > 1) {
      // 縮放圖片 此處用到平方根 將寬帶和高度壓縮掉對應(yīng)的平方根倍
      // (保持寬高不變,縮放后也達(dá)到了最大占用空間的大?。?      return scaleWithWH(bitmap,bitmap.getWidth() / Math.sqrt(i),
              bitmap.getHeight() / Math.sqrt(i));
    }
    return null;
  }

  /***
   * 圖片縮放
   *@param bitmap 位圖
   * @param w 新的寬度
   * @param h 新的高度
   * @return Bitmap
   */
  public static Bitmap scaleWithWH(Bitmap bitmap, double w, double h) {
    if (w == 0 || h == 0 || bitmap == null) {
      return bitmap;
    } else {
      int width = bitmap.getWidth();
      int height = bitmap.getHeight();

      Matrix matrix = new Matrix();
      float scaleWidth = (float) (w / width);
      float scaleHeight = (float) (h / height);
      
      matrix.postScale(scaleWidth, scaleHeight);
      return Bitmap.createBitmap(bitmap, 0, 0, width, height,
          matrix, true);
    }
  }

  /**
   * YUV視頻流格式轉(zhuǎn)bitmap
   * @param data YUV視頻流格式
   * @return width 設(shè)置寬度
   * @return width 設(shè)置高度
   */
  public static Bitmap getBitmap(byte[] data, int width, int height) {
    Bitmap bitmap;
    YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, width, height, null);
    //data是onPreviewFrame參數(shù)提供
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    yuvimage.compressToJpeg(new Rect(0, 0, yuvimage.getWidth(), yuvimage.getHeight()), 100, baos);//
    // 80--JPG圖片的質(zhì)量[0-100],100最高
    byte[] rawImage = baos.toByteArray();
    BitmapFactory.Options options = new BitmapFactory.Options();
    SoftReference<Bitmap> softRef = new SoftReference<Bitmap>(BitmapFactory.decodeByteArray(rawImage, 0, rawImage
        .length, options));
    bitmap = softRef.get();
    return bitmap;
  }

  /**
   * 圖片路徑轉(zhuǎn)bitmap
   * @param file 圖片的絕對路徑
   * @return bitmap
   */
  public static Bitmap getAssetImage(String file) {
    Bitmap bitmap = null;
    AssetManager am = mActivity.getAssets();
    try {
      InputStream is = am.open(file);
      bitmap = BitmapFactory.decodeStream(is);
      is.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return bitmap;
  }

  /**
   * bitmap保存到指定路徑
   * @param file 圖片的絕對路徑
   * @param file 位圖
   * @return bitmap
   */
  public static boolean saveFile(String file, Bitmap bmp) {
    if(TextUtils.isEmpty(file) || bmp == null) return false;
    
    File f = new File(file);
    if (f.exists()) {
      f.delete();
    }else {
      File p = f.getParentFile();
      if(!p.exists()) {
        p.mkdirs();
      }
    }
    try {
      FileOutputStream out = new FileOutputStream(f);
      bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
      out.flush();
      out.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return false;
    }
    return true;
  }

  /**
   * 回收一個(gè)未被回收的Bitmap
   *@param bitmap
   */
  public static void doRecycledIfNot(Bitmap bitmap) {
    if (!bitmap.isRecycled()) {
      bitmap.recycle();
    }
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI