Android Bitmap 圖片處理工具類

jopen 9年前發布 | 14K 次閱讀 Java Android

將Drawable轉為Bitmap

public static Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap
                .createBitmap(
                        drawable.getIntrinsicWidth(),
                        drawable.getIntrinsicHeight(),
                        drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                                : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        // canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }

將Bitmap轉為btye[]

 public static byte[] bmpToByteArray(final Bitmap bmp,
            final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(CompressFormat.JPEG, 80, output);
        if (needRecycle) {
            bmp.recycle();
        }
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

將圖片存儲到sdcard中

 public static void storeImageToSDCARD(Bitmap colorImage, String ImageName,
            String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        File imagefile = new File(file, ImageName + ".jpg");
        try {
            imagefile.createNewFile();
            FileOutputStream fos = new FileOutputStream(imagefile);
            colorImage.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

sdcard取圖片

  public static Bitmap getImg(String path,String picName) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return null;
        }
        try {
            File file = new File(path, picName + ".png");
            FileInputStream inputStream = new FileInputStream(file);
            byte[] b = new byte[inputStream.available()];
            inputStream.read(b);
            Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
            return bitmap;
        } catch (Exception e) {
            return null;
        }
    }

網絡獲取圖片

public static Bitmap getImageByNet(String urlpath) throws Exception {
        URL url = new URL(urlpath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5 * 1000);
        Bitmap bitmap = null;
        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);
        }
        return bitmap;
    }

將兩個bitmap對象整合并保存為一張圖片


  public Bitmap combineBitmap(Bitmap background, Bitmap foreground) {
        //第一張圖片的寬高
        int bgWidth = background.getWidth();
        int bgHeight = background.getHeight();
        //第二章圖片的寬高
        int fgWidth = foreground.getWidth();
        int fgHeight = foreground.getHeight();
        //創建一個新的bitmao  高度等于兩張高度的總和 用來豎列拼接
        Bitmap newmap = Bitmap.createBitmap(bgWidth, bgHeight + fgHeight,
                android.graphics.Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newmap);
        //畫上第一張圖片
        canvas.drawBitmap(background, 0, 0, null);
        //從第一張圖片的下邊開始畫入第二張圖片
        canvas.drawBitmap(foreground, 0, bgHeight, null);
        return newmap;
    }

Bitmap旋轉一定角度

 public static Bitmap rotate(Bitmap b, int degrees) {
        if (degrees != 0 && b != null) {
            Matrix m = new Matrix();
            m.setRotate(degrees, (float) b.getWidth() / 2,
                    (float) b.getHeight() / 2);
            try {
                Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(),
                        b.getHeight(), m, true);
                return b2;// 正常情況下返回旋轉角度的圖
            } catch (OutOfMemoryError ex) {
                return b;// 內存溢出返回原圖
            } finally {
                b.recycle();// 釋放資源
            }
        }
        return b;
    }

Bitmap畫一個圓角圖

 public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
        if (bitmap == null) {
            return bitmap;
        }
        try {
            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
                    bitmap.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(output);
            final int color = 0xff424242;
            final Paint paint = new Paint();
            final Rect rect = new Rect(0, 0, bitmap.getWidth(),
                    bitmap.getHeight());
            final RectF rectF = new RectF(rect);
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
            return output;
        } catch (OutOfMemoryError e) {
            // TODO: handle exception
            System.gc();
            return null;
        }
    }

從view 得到圖片

 public static Bitmap getBitmapFromView(View view) {
        view.destroyDrawingCache();
        view.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = view.getDrawingCache(true);
        return bitmap;
    }

添加水印

  public static Bitmap watermarkBitmap(Bitmap src, Bitmap watermark,
            String title) {
        if (src == null) {
            return null;
        }
        int w = src.getWidth();
        int h = src.getHeight();
        // 需要處理圖片太大造成的內存超過的問題,這里我的圖片很小所以不寫相應代碼了
        Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 創建一個新的和SRC長度寬度一樣的位圖
        Canvas cv = new Canvas(newb);
        cv.drawBitmap(src, 0, 0, null);// 在 0,0坐標開始畫入src
        Paint paint = new Paint();
        // 加入圖片
        if (watermark != null) {
            int ww = watermark.getWidth();
            int wh = watermark.getHeight();
            paint.setAlpha(50);
            cv.drawBitmap(watermark, w - ww + 5, h - wh + 5, paint);// 在src的右下角畫入水印
        }
        // 加入文字
        if (title != null) {
            String familyName = "宋體";
            Typeface font = Typeface.create(familyName, Typeface.BOLD);
            TextPaint textPaint = new TextPaint();
            textPaint.setColor(Color.RED);
            textPaint.setTypeface(font);
            textPaint.setTextSize(22);
            // 這里是自動換行的
            StaticLayout layout = new StaticLayout(title, textPaint, w,
                    Alignment.ALIGN_NORMAL, 1.0F, 0.0F, true);
            layout.draw(cv);
            // 文字就加左上角算了
            // cv.drawText(title,0,40,paint);
        }
        cv.save(Canvas.ALL_SAVE_FLAG);// 保存
        cv.restore();// 存儲
        return newb;
    }

等比例壓縮圖片

      public static Bitmap getBitmap(Bitmap bitmap, int screenWidth,
            int screenHight) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Matrix matrix = new Matrix();
        float scale = (float) screenWidth / w;
        float scale2 = (float) screenHight / h;

        //取比例小的值 可以把圖片完全縮放在屏幕內
        scale = scale < scale2 ? scale : scale2;

        // 都按照寬度scale 保證圖片不變形.根據寬度來確定高度
        matrix.postScale(scale, scale);
        // w,h是原圖的屬性.
        return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
    }
以最省內存的方式讀取本地資源的圖片

        public static Bitmap ReadBitmapById(Context context, int drawableId,
            int screenWidth, int screenHight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Config.ARGB_8888;
        options.inInputShareable = true;
        options.inPurgeable = true;
        InputStream stream = context.getResources().openRawResource(drawableId);
        Bitmap bitmap = BitmapFactory.decodeStream(stream, null, options);
        return getBitmap(bitmap, screenWidth, screenHight);
    }


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!