Here you can find the source of cutImg(File file, int newWidth, int newHeight)
public static Bitmap cutImg(File file, int newWidth, int newHeight)
/*//from w ww.j a v a 2 s. co m * Copyright (C) 2013 www.418log.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http: * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import android.graphics.Bitmap; import android.graphics.BitmapFactory; public class Main { public static Bitmap cutImg(File file, int newWidth, int newHeight) { Bitmap resizeBmp = null; if (newWidth <= 0 || newHeight <= 0) { throw new IllegalArgumentException( "0"); } BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeFile(file.getPath(), opts); int srcWidth = opts.outWidth; int srcHeight = opts.outHeight; int destWidth = 0; int destHeight = 0; int cutSrcWidth = newWidth * 2; int cutSrcHeight = newHeight * 2; double ratio = 0.0; if (srcWidth < cutSrcWidth || srcHeight < cutSrcHeight) { ratio = 0.0; destWidth = srcWidth; destHeight = srcHeight; } else if (srcWidth > cutSrcWidth) { ratio = (double) srcWidth / cutSrcWidth; destWidth = cutSrcWidth; destHeight = (int) (srcHeight / ratio); } else if (srcHeight > cutSrcHeight) { ratio = (double) srcHeight / cutSrcHeight; destHeight = cutSrcHeight; destWidth = (int) (srcWidth / ratio); } opts.inPreferredConfig = Bitmap.Config.RGB_565; opts.inPurgeable = true; opts.inInputShareable = true; if (ratio > 1) { opts.inSampleSize = (int) ratio; } else { opts.inSampleSize = 1; } opts.outHeight = destHeight; opts.outWidth = destWidth; opts.inJustDecodeBounds = false; opts.inDither = false; Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), opts); if (bitmap != null) { resizeBmp = cutImg(bitmap, newWidth, newHeight); } return resizeBmp; } public static Bitmap cutImg(Bitmap bitmap, int newWidth, int newHeight) { if (bitmap == null) { return null; } if (newWidth <= 0 || newHeight <= 0) { throw new IllegalArgumentException( "0"); } Bitmap resizeBmp = null; try { int width = bitmap.getWidth(); int height = bitmap.getHeight(); if (width <= 0 || height <= 0) { return null; } int offsetX = 0; int offsetY = 0; if (width > newWidth) { offsetX = (width - newWidth) / 2; } else { newWidth = width; } if (height > newHeight) { offsetY = (height - newHeight) / 2; } else { newHeight = height; } resizeBmp = Bitmap.createBitmap(bitmap, offsetX, offsetY, newWidth, newHeight); } catch (Exception e) { e.printStackTrace(); } finally { if (resizeBmp != bitmap) { bitmap.recycle(); } } return resizeBmp; } }