对Bitmap的封装

来源:互联网 发布:php项目经验 编辑:程序博客网 时间:2024/05/19 23:29
/** *按比例缩放图片  * * */public static Bitmap getScaledBitmap(Bitmap oldBmp, int newWidth) {    int oldWidth = oldBmp.getWidth();    int oldHeight = oldBmp.getHeight();    float scale = (float) oldHeight / oldWidth;    int newHeight = Math.round(newWidth * scale);    Bitmap newBmp = Bitmap.createScaledBitmap(oldBmp, newWidth, newHeight, false);    oldBmp.recycle();    return newBmp;

}

/*** *  url转换成bitmap *  * */public final static Bitmap returnBitMap(String url) {   URL myFileUrl = null;   Bitmap bitmap = null;   try {      myFileUrl = new URL(url);      HttpURLConnection conn;      conn = (HttpURLConnection) myFileUrl.openConnection();      conn.setDoInput(true);      conn.connect();      InputStream is = conn.getInputStream();      bitmap = BitmapFactory.decodeStream(is);   } catch (MalformedURLException e) {      // TODO Auto-generated catch block      e.printStackTrace();   }  catch (IOException e) {      // TODO Auto-generated catch block      e.printStackTrace();   }   return bitmap;}
/** * 旋转Bitmap * @param b * @param rotateDegree * @return */public static Bitmap getRotateBitmap(Bitmap b, float rotateDegree){   if(b==null)      return null;   Matrix matrix = new Matrix();   matrix.postRotate(rotateDegree);   Bitmap rotaBitmap = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, false);   return rotaBitmap;}
public class BitmapUtil {    /**     * 缩放图片到指定的长宽,keep为true,保持长宽比     *      * @param bm     * @param width     * @param height     * @param keep     * @return     */    public static Bitmap scale(Bitmap bm, int width, int height, boolean keep) {        // 获得图片的宽高        int w = bm.getWidth();        int h = bm.getHeight();        // 计算缩放比例        float scaleWidth = ((float) width) / w;        float scaleHeight = ((float) height) / h;        if (keep) {            float s = Math.max(scaleWidth, scaleHeight);            scaleWidth = s;            scaleHeight = s;        }        // 取得想要缩放的matrix参数        Matrix matrix = new Matrix();        matrix.postScale(scaleWidth, scaleHeight);        // 得到新的图片        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, w, h, matrix, true);        return newbm;    }    /**     * 缩放图片 指定最大长度     *      * @param bm     * @param max     * @return     */    public static Bitmap scale(Bitmap bm, int max) {        // 获得图片的宽高        int width = bm.getWidth();        int height = bm.getHeight();        // 计算缩放比例        float scaleWidth = 1;        float scaleHeight = 1;        if (width > height) {            scaleWidth = ((float) max) / width;            scaleHeight = scaleWidth;        } else {            scaleHeight = scaleWidth = ((float) max) / height;        }        // 取得想要缩放的matrix参数        Matrix matrix = new Matrix();        matrix.postScale(scaleWidth, scaleHeight);        // 得到新的图片        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);        return newbm;    }    /**     * 缩放图片 in samplesize     *      * @param orifile     * @param descFile     * @param sampleSize     * @return     */    public static File scale(File orifile, File descFile, int sampleSize) {        BitmapFactory.Options options = new BitmapFactory.Options();        options.inSampleSize = sampleSize;        Bitmap bitmap = BitmapFactory.decodeFile(orifile.getAbsolutePath(), options);        BufferedOutputStream bos = null;        try {            bos = new BufferedOutputStream(new FileOutputStream(descFile));            bitmap.compress(CompressFormat.JPEG, 80, bos);        } catch (FileNotFoundException e) {            e.printStackTrace();        } finally {            if (bos != null) {                try {                    bos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            bitmap.recycle();        }        return descFile;    }    /**     * 缩小图片     *      * @param orifile     * @param descFile     * @param maxWidth     * @param maxHeight     * @return     */    public static File scale(File orifile, File descFile, int maxWidth, int maxHeight) {        Bitmap bitmap = getSmallBitmap(orifile.getAbsolutePath(), maxWidth, maxHeight);        saveBitmap(bitmap, descFile);        return descFile;    }    public static int computeSampleSize(File file, int maxsize) {        int initialSize = (int) ((float) (file.length() / 1000) / (float) maxsize + 0.5);        int roundedSize;        if (initialSize <= 8) {            roundedSize = 1;            while (roundedSize < initialSize) {                roundedSize <<= 1;            }        } else {            roundedSize = (initialSize + 7) / 8 * 8;        }        return roundedSize;    }    /**     * convert Bitmap to byte array     */    public static byte[] bitmapToByte(Bitmap b) {        ByteArrayOutputStream o = new ByteArrayOutputStream();        b.compress(Bitmap.CompressFormat.PNG, 100, o);        return o.toByteArray();    }    /**     * convert byte array to Bitmap     */    public static Bitmap byteToBitmap(byte[] b) {        return (b == null || b.length == 0) ? null : BitmapFactory.decodeByteArray(b, 0, b.length);    }    /**     * 把bitmap转换成Base64编码String     */    public static String bitmapToString(Bitmap bitmap) {        return Base64.encodeToString(bitmapToByte(bitmap), Base64.DEFAULT);    }    /**     * convert Drawable to Bitmap     */    public static Bitmap drawableToBitmap(Drawable drawable) {        return drawable == null ? null : ((BitmapDrawable) drawable).getBitmap();    }    /**     * convert Bitmap to Drawable     */    @SuppressWarnings("deprecation")    public static Drawable bitmapToDrawable(Bitmap bitmap) {        return bitmap == null ? null : new BitmapDrawable(bitmap);    }    /**     * scale image     */    public static Bitmap scaleImageTo(Bitmap org, int newWidth, int newHeight) {        return scaleImage(org, (float) newWidth / org.getWidth(), (float) newHeight / org.getHeight());    }    /**     * scale image     */    public static Bitmap scaleImage(Bitmap org, float scaleWidth, float scaleHeight) {        if (org == null) {            return null;        }        Matrix matrix = new Matrix();        matrix.postScale(scaleWidth, scaleHeight);        return Bitmap.createBitmap(org, 0, 0, org.getWidth(), org.getHeight(), matrix, true);    }    public static Bitmap toRoundCorner(Bitmap bitmap) {        int height = bitmap.getHeight();        int width = bitmap.getHeight();        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);        Canvas canvas = new Canvas(output);        final Paint paint = new Paint();        final Rect rect = new Rect(0, 0, width, height);        paint.setAntiAlias(true);        canvas.drawARGB(0, 0, 0, 0);        paint.setColor(0xff424242);        // paint.setColor(Color.TRANSPARENT);        canvas.drawCircle(width / 2, height / 2, width / 2, paint);        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));        canvas.drawBitmap(bitmap, rect, rect, paint);        return output;    }    public static Bitmap createBitmapThumbnail(Bitmap bitMap, boolean needRecycle) {        int width = bitMap.getWidth();        int height = bitMap.getHeight();        // 设置想要的大小        int newWidth = 120;        int newHeight = 120;        // 计算缩放比例        float scaleWidth = ((float) newWidth) / width;        float scaleHeight = ((float) newHeight) / height;        // 取得想要缩放的matrix参数        Matrix matrix = new Matrix();        matrix.postScale(scaleWidth, scaleHeight);        // 得到新的图片        Bitmap newBitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height, matrix, true);        if (needRecycle)            bitMap.recycle();        return newBitMap;    }    /**     * 压缩并保存图片到文件     *     * **/    public static boolean saveBitmap(Bitmap bitmap, File file) {        if (bitmap == null)            return false;        FileOutputStream fos = null;        try {            fos = new FileOutputStream(file);            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);            fos.flush();            return true;        } catch (Exception e) {            e.printStackTrace();        } finally {            if (fos != null) {                try {                    fos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return false;    }    /**     *      * @param bitmap     * @param file     * @param quality     *            0-100     * @param format     *            jpg,png  压缩图片并保存到文件里面  format 是图片格式  quelity是压缩的程度 file是压缩之后放到这个file里面  bitmap就是被压缩的图片     * @return     */    public static boolean saveBitmap(Bitmap bitmap, File file, int quality, String format) {        if (bitmap == null)            return false;        FileOutputStream fos = null;        try {            fos = new FileOutputStream(file);            if ("jpg".equals(format)) {                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, fos);            } else {                bitmap.compress(Bitmap.CompressFormat.PNG, quality, fos);            }            fos.flush();            return true;        } catch (Exception e) {            e.printStackTrace();        } finally {            if (fos != null) {                try {                    fos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return false;    }    public static boolean saveBitmap(Bitmap bitmap, String absPath) {        return saveBitmap(bitmap, new File(absPath));    }    /**     * 计算图片的缩放值 如果图片的原始高度或者宽度大与我们期望的宽度和高度,我们需要计算出缩放比例的数值。否则就不缩放。     * heightRatio是图片原始高度与压缩后高度的倍数, widthRatio是图片原始宽度与压缩后宽度的倍数。     * inSampleSize就是缩放值 ,取heightRatio与widthRatio中最小的值。     * inSampleSize为1表示宽度和高度不缩放,为2表示压缩后的宽度与高度为原来的1/2(图片为原1/4)。     *      * @param options     * @param reqWidth     * @param reqHeight     * @return     */    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {        // Raw height and width of image        final int height = options.outHeight;        final int width = options.outWidth;        int inSampleSize = 1;        if (height > reqHeight || width > reqWidth) {            // Calculate ratios of height and width to requested height and            // width            final int heightRatio = Math.round((float) height / (float) reqHeight);            final int widthRatio = Math.round((float) width / (float) reqWidth);            // Choose the smallest ratio as inSampleSize value, this will            // guarantee            // a final image with both dimensions(尺寸) larger than or equal to            // the requested height and width.            inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;        }        return inSampleSize;    }    /**     * 根据路径获得图片并压缩返回bitmap用于显示     *      * @return     */    public static Bitmap getSmallBitmap(String filePath, int w, int h) {        final BitmapFactory.Options options = new BitmapFactory.Options();        // 该值设为true那么将不返回实际的bitmap不给其分配内存空间而里面只包括一些解码边界信息即图片大小信息        options.inJustDecodeBounds = true;// inJustDecodeBounds设置为true,可以不把图片读到内存中,但依然可以计算出图片的大小        BitmapFactory.decodeFile(filePath, options);        // Calculate inSampleSize        options.inSampleSize = calculateInSampleSize(options, w, h);        // Decode bitmap with inSampleSize set        options.inJustDecodeBounds = false;// 重新读入图片,注意这次要把options.inJustDecodeBounds                                           // 设为 false        Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);// BitmapFactory.decodeFile()按指定大小取得图片缩略图        return bitmap;    }    public static Intent buildGalleryPickIntent(Uri saveTo, int aspectX, int aspectY, int outputX, int outputY,            boolean returnData) {        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);        intent.setType("image/*");        intent.putExtra("crop", "true");        intent.putExtra("output", saveTo);        intent.putExtra("aspectX", aspectX);        intent.putExtra("aspectY", aspectY);        intent.putExtra("outputX", outputX);        intent.putExtra("outputY", outputY);        intent.putExtra("scale", true);        intent.putExtra("return-data", returnData);        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());        return intent;    }    public static Intent buildImagePickIntent(Uri uriFrom, Uri uriTo, int aspectX, int aspectY, int outputX,            int outputY, boolean returnData) {        Intent intent = new Intent("com.android.camera.action.CROP");        intent.setDataAndType(uriFrom, "image/*");        intent.putExtra("crop", "true");        intent.putExtra("output", uriTo);        intent.putExtra("aspectX", aspectX);        intent.putExtra("aspectY", aspectY);        intent.putExtra("outputX", outputX);        intent.putExtra("outputY", outputY);        intent.putExtra("scale", true);        intent.putExtra("return-data", returnData);        intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());        return intent;    }    public static Intent buildCaptureIntent(Uri uri) {        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);        return intent;    }    public static Bitmap toGrayscale(Bitmap bmpOriginal) {        int width, height;        height = bmpOriginal.getHeight();        width = bmpOriginal.getWidth();        Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);        Canvas c = new Canvas(bmpGrayscale);        Paint paint = new Paint();        ColorMatrix cm = new ColorMatrix();        cm.setSaturation(0);        ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);        paint.setColorFilter(f);        c.drawBitmap(bmpOriginal, 0, 0, paint);        return bmpGrayscale;    }    /**     * 图片锐化(拉普拉斯变换)     *      * @param bmp     * @return     */    public static Bitmap sharpenImageAmeliorate(Bitmap bmp) {        long start = System.currentTimeMillis();        // 拉普拉斯矩阵        int[] laplacian = new int[] { -1, -1, -1, -1, 9, -1, -1, -1, -1 };        int width = bmp.getWidth();        int height = bmp.getHeight();        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);        int pixR = 0;        int pixG = 0;        int pixB = 0;        int pixColor = 0;        int newR = 0;        int newG = 0;        int newB = 0;        int idx = 0;        float alpha = 0.3F;        int[] pixels = new int[width * height];        bmp.getPixels(pixels, 0, width, 0, 0, width, height);        for (int i = 1, length = height - 1; i < length; i++) {            for (int k = 1, len = width - 1; k < len; k++) {                idx = 0;                for (int m = -1; m <= 1; m++) {                    for (int n = -1; n <= 1; n++) {                        pixColor = pixels[(i + n) * width + k + m];                        pixR = Color.red(pixColor);                        pixG = Color.green(pixColor);                        pixB = Color.blue(pixColor);                        newR = newR + (int) (pixR * laplacian[idx] * alpha);                        newG = newG + (int) (pixG * laplacian[idx] * alpha);                        newB = newB + (int) (pixB * laplacian[idx] * alpha);                        idx++;                    }                }                newR = Math.min(255, Math.max(0, newR));                newG = Math.min(255, Math.max(0, newG));                newB = Math.min(255, Math.max(0, newB));                pixels[i * width + k] = Color.argb(255, newR, newG, newB);                newR = 0;                newG = 0;                newB = 0;            }        }        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);        long end = System.currentTimeMillis();        Log.d("may", "used time=" + (end - start));        return bitmap;    }    public static Bitmap changeGrey(Bitmap bm) {        int threashold = 80;        int width = bm.getWidth();        // int height = bm.getHeight();        // convert image into gray        Paint p = new Paint();        ColorMatrix cm = new ColorMatrix();        cm.setSaturation(0);        ColorMatrixColorFilter filter = new ColorMatrixColorFilter(cm);        p.setColorFilter(filter);        // binaryzation        int[] colors = new int[bm.getWidth()];        for (int i = 0; i < bm.getHeight(); i++) {            bm.getPixels(colors, 0, width, 0, i, width, 1);            for (int j = 0; j < bm.getWidth(); j++) {                int red = Color.red(colors[j]);                if (red > threashold) {                    red = 255;                } else {                    red = 0;                }                colors[j] = Color.argb(255, red, red, red);            }            bm.setPixels(colors, 0, width, 0, i, width, 1);        }        return bm;    }    public static Bitmap binarization(Bitmap img) {        int width = img.getWidth();        int height = img.getHeight();        int area = width * height;        int gray[][] = new int[width][height];        int average = 0;// 灰度平均值        int graysum = 0;        int graymean = 0;        int grayfrontmean = 0;        int graybackmean = 0;        int pixelGray;        int front = 0;        int back = 0;        int[] pix = new int[width * height];        img.getPixels(pix, 0, width, 0, 0, width, height);        for (int i = 1; i < width; i++) { // 不算边界行和列,为避免越界            for (int j = 1; j < height; j++) {                int x = j * width + i;                int r = (pix[x] >> 16) & 0xff;                int g = (pix[x] >> 8) & 0xff;                int b = pix[x] & 0xff;                pixelGray = (int) (0.3 * r + 0.59 * g + 0.11 * b);// 计算每个坐标点的灰度                gray[i][j] = (pixelGray << 16) + (pixelGray << 8) + (pixelGray);                graysum += pixelGray;            }        }        graymean = (int) (graysum / area);// 整个图的灰度平均值        average = graymean;        for (int i = 0; i < width; i++) // 计算整个图的二值化阈值        {            for (int j = 0; j < height; j++) {                if (((gray[i][j]) & (0x0000ff)) < graymean) {                    graybackmean += ((gray[i][j]) & (0x0000ff));                    back++;                } else {                    grayfrontmean += ((gray[i][j]) & (0x0000ff));                    front++;                }            }        }        int frontvalue = (int) (grayfrontmean / front);// 前景中心        int backvalue = (int) (graybackmean / back);// 背景中心        float G[] = new float[frontvalue - backvalue + 1];// 方差数组        int s = 0;        for (int i1 = backvalue; i1 < frontvalue + 1; i1++)// 以前景中心和背景中心为区间采用大津法算法(OTSU算法)        {            back = 0;            front = 0;            grayfrontmean = 0;            graybackmean = 0;            for (int i = 0; i < width; i++) {                for (int j = 0; j < height; j++) {                    if (((gray[i][j]) & (0x0000ff)) < (i1 + 1)) {                        graybackmean += ((gray[i][j]) & (0x0000ff));                        back++;                    } else {                        grayfrontmean += ((gray[i][j]) & (0x0000ff));                        front++;                    }                }            }            grayfrontmean = (int) (grayfrontmean / front);            graybackmean = (int) (graybackmean / back);            G[s] = (((float) back / area) * (graybackmean - average) * (graybackmean - average) + ((float) front / area)                    * (grayfrontmean - average) * (grayfrontmean - average));            s++;        }        float max = G[0];        int index = 0;        for (int i = 1; i < frontvalue - backvalue + 1; i++) {            if (max < G[i]) {                max = G[i];                index = i;            }        }        for (int i = 0; i < width; i++) {            for (int j = 0; j < height; j++) {                int in = j * width + i;                if (((gray[i][j]) & (0x0000ff)) < (index + backvalue)) {                    pix[in] = Color.rgb(0, 0, 0);                } else {                    pix[in] = Color.rgb(255, 255, 255);                }            }        }        Bitmap temp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);        temp.setPixels(pix, 0, width, 0, 0, width, height);        return temp;    }    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {        try {            Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);            Canvas canvas = new Canvas(output);            final Paint paint = new Paint();            final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());            final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()));            paint.setAntiAlias(true);            canvas.drawARGB(0, 0, 0, 0);            paint.setColor(Color.BLACK);            canvas.drawRoundRect(rectF, roundPx, roundPx, paint);            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));            final Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());            canvas.drawBitmap(bitmap, src, rect, paint);            return output;        } catch (Exception e) {            return bitmap;        }    }    /**     * 简单计算清晰度     *      * @param bmp     * @return     */    public static boolean getClearness(Bitmap bmp) {        int width = bmp.getWidth();        int height = bmp.getHeight();// 得到图片的长宽        int pixel, pixel1;// pixel1是当前像素点颜色 pixel是相邻的像素点颜色        // 拉普拉斯模板        // int[] Laplacian = { -1, -1, -1, -1, 9, -1, -1, -1, -1 };//        int[] Laplacian = { -1, 3, -1 };//        int count = 0;        for (int x = 1; x < width - 1; x++) {            for (int y = 1; y < height - 1; y++) {// 循环图片的每个像素点                int r = 0, g = 0, b = 0;                int Index = 0;                pixel1 = bmp.getPixel(x, y);                // for (int col = -1; col <= 1; col++) {                for (int row = -1; row <= 1; row++) {// 循环每个像素相邻的8个像素                    pixel = bmp.getPixel(x + row, y);// 得到相邻像素的颜色                    r += Color.red(pixel) * Laplacian[Index];                    g += Color.green(pixel) * Laplacian[Index];                    b += Color.blue(pixel) * Laplacian[Index];                    Index++;                }                // }                r = Math.abs(Color.red(pixel1) - r) + Math.abs(Color.green(pixel1) - g)                        + Math.abs(Color.blue(pixel1) - b);// 得到相邻像素RGB的平均值                                                           // 与当前像素RGB值相减                if (r > 100)                    count++;// 绝对值超过120我算它是可识别的 120是我随意定的一个值            }        }        int percent = count * 100 / (width * height);        Log.d("bitmapUtil", "clearness:" + percent);        if (percent < 2)// 简单统计出来的数据            return false;        else            return true;    }    public static int[] getBitmapSize(String path) {        BitmapFactory.Options options = new BitmapFactory.Options();        options.inJustDecodeBounds = true;        BitmapFactory.decodeFile(path, options);        int[] size = new int[2];        size[0] = options.outWidth;        size[1] = options.outHeight;        return size;    }    @SuppressLint("NewApi")    public static Bitmap readRegionBitmap(ContentResolver resolver, Uri inUri, int max, Rect roundedTrueCrop) {        float width = roundedTrueCrop.right - roundedTrueCrop.left;        float height = roundedTrueCrop.bottom - roundedTrueCrop.top;        float initialSize = Math.max(width, height) / (float) max;        int inSampleSize;        if (initialSize <= 8) {            inSampleSize = 1;            while (inSampleSize < initialSize) {                inSampleSize <<= 1;            }        } else {            inSampleSize = ((int) initialSize + 7) / 8 * 8;        }        LogUtil.e("xbin:inSampleSize=" + inSampleSize + " initialSize=" + initialSize + " w=" + width + " h=" + height);        // Attempt to open a region decoder        BitmapRegionDecoder decoder = null;        InputStream is = null;        try {            is = resolver.openInputStream(inUri);            decoder = BitmapRegionDecoder.newInstance(is, true);        } catch (IOException e) {            e.printStackTrace();        } finally {            if (is != null) {                try {                    is.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        Bitmap crop = null;        if (decoder != null) {            // Do region decoding to get crop bitmap            BitmapFactory.Options options = new BitmapFactory.Options();            if (Build.VERSION.SDK_INT > 10) {                options.inMutable = true;            }            options.inJustDecodeBounds = false;            options.inSampleSize = inSampleSize;            crop = decoder.decodeRegion(roundedTrueCrop, options);            decoder.recycle();        }        return crop;    }}

0 0