編輯:關於 Android 開發
在專案中調用相機拍照後,返回的圖片往往尺寸龐大,不利於上傳與儲存。這時就需要對圖片進行壓縮、裁剪與格式轉換。以下整理了幾個常用做法,並提供一個功能完整的 ImageUtils 工具類。
從 SD 卡直接取得 Bitmap:
// 從SD卡裡直接獲取Bitmap
private Bitmap getDiskBitmap(String pathString) {
Bitmap bitmap = null;
try {
File file = new File(pathString);
if (file.exists()) {
bitmap = BitmapFactory.decodeFile(pathString);
}
} catch (Exception e) {
// TODO: handle exception
}
return bitmap;
}
將 Bitmap 轉換成 Base64 字串:
// 轉換成64位的Bitmap
public static String bitmapToBase64(Bitmap bitmap) {
String result = null;
ByteArrayOutputStream baos = null;
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baos.flush();
baos.close();
byte[] bitmapBytes = baos.toByteArray();
result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
依比例裁剪圖片:
// 裁剪
public static Bitmap imageCrop(Bitmap bitmap, int num1, int num2, boolean isRecycled) {
if (bitmap == null) {
return null;
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int retX, retY;
int nw, nh;
if (w > h) {
if (h > w * num2 / num1) {
nw = w;
nh = w * num2 / num1;
retX = 0;
retY = (h - nh) / 2;
} else {
nw = h * num1 / num2;
nh = h;
retX = (w - nw) / 2;
retY = 0;
}
} else {
if (w > h * num2 / num1) {
nh = h;
nw = h * num2 / num1;
retY = 0;
retX = (w - nw) / 2;
} else {
nh = w * num1 / num2;
nw = w;
retY = (h - nh) / 2;
retX = 0;
}
}
Bitmap bmp = Bitmap.createBitmap(bitmap, retX, retY, nw, nh, null, false);
if (isRecycled && bitmap != null && !bitmap.equals(bmp) && !bitmap.isRecycled()) {
bitmap.recycle();// 回收原圖片
bitmap = null;
}
return bmp;
}
使用時的串接範例:
private void encode() {
File file = new File(Environment.getExternalStorageDirectory(),"famous_bitmap_painting.jpg");
try {
if (file.exists()) {
file.delete();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
String imgPath = getIntent().getStringExtra("famousPicturePath");
String imgBitmapPath = file.getPath().toString();
try {
ImageUtils.createImageThumbnail(getApplicationContext(), imgPath, imgBitmapPath, 500, 100);
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bitmap = getDiskBitmap(imgBitmapPath);
if (bitmap != null) {
Bitmap bitmap2 = imageCrop(bitmap, 500, 500, false);
search_img.setImageBitmap(bitmap2);
String base64 = bitmapToBase64(bitmap);
}
}
以下為功能完整的 ImageUtils,涵蓋存檔、讀取、縮放、裁剪、圓角、倒影、格式判斷等常用操作,可依需求取用:
public class ImageUtils {
public final static String SDCARD_MNT = "/mnt/sdcard";
public final static String SDCARD = "/sdcard";
public static final int REQUEST_CODE_GETIMAGE_BYSDCARD = 0;
public static final int REQUEST_CODE_GETIMAGE_BYCAMERA = 1;
public static final int REQUEST_CODE_GETIMAGE_BYCROP = 2;
public static final int REQUEST_CODE_GETIMAGE_IMAGEPAVER = 3;
public static void saveImage(Context context, String fileName, Bitmap bitmap) throws IOException {
saveImage(context, fileName, bitmap, 100);
}
public static void saveImage(Context context, String fileName, Bitmap bitmap, int quality) throws IOException {
if (bitmap == null || fileName == null || context == null) return;
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, quality, stream);
byte[] bytes = stream.toByteArray();
fos.write(bytes);
fos.close();
}
public static void saveImageToSD(Context ctx, String filePath, Bitmap bitmap, int quality) throws IOException {
if (bitmap != null) {
File file = new File(filePath.substring(0, filePath.lastIndexOf(File.separator)));
if (!file.exists()) {
file.mkdirs();
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
bitmap.compress(CompressFormat.JPEG, quality, bos);
bos.flush();
bos.close();
if (ctx != null) {
scanPhoto(ctx, filePath);
}
}
}
private static void scanPhoto(Context ctx, String imgFileName) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File file = new File(imgFileName);
Uri contentUri = Uri.fromFile(file);
mediaScanIntent.setData(contentUri);
ctx.sendBroadcast(mediaScanIntent);
}
public static Bitmap getBitmap(Context context, String fileName) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
fis = context.openFileInput(fileName);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try { fis.close(); } catch (Exception e) { }
}
return bitmap;
}
public static Bitmap getBitmapByPath(String filePath) {
return getBitmapByPath(filePath, null);
}
public static Bitmap getBitmapByPath(String filePath, BitmapFactory.Options opts) {
FileInputStream fis = null;
Bitmap bitmap = null;
try {
File file = new File(filePath);
fis = new FileInputStream(file);
bitmap = BitmapFactory.decodeStream(fis, null, opts);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
} finally {
try { fis.close(); } catch (Exception e) { }
}
return bitmap;
}
public static String getTempFileName() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SS");
return format.format(new Timestamp(System.currentTimeMillis()));
}
public static String getCamerPath() {
return Environment.getExternalStorageDirectory() + File.separator + "FounderNews" + File.separator;
}
public static int[] scaleImageSize(int[] img_size, int square_size) {
if (img_size[0] <= square_size && img_size[1] <= square_size) return img_size;
double ratio = square_size / (double) Math.max(img_size[0], img_size[1]);
return new int[] { (int) (img_size[0] * ratio), (int) (img_size[1] * ratio) };
}
public static void createImageThumbnail(Context context, String largeImagePath, String thumbfilePath, int square_size, int quality) throws IOException {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 1;
Bitmap cur_bitmap = getBitmapByPath(largeImagePath, opts);
if (cur_bitmap == null) return;
int[] cur_img_size = new int[] { cur_bitmap.getWidth(), cur_bitmap.getHeight() };
int[] new_img_size = scaleImageSize(cur_img_size, square_size);
Bitmap thb_bitmap = zoomBitmap(cur_bitmap, new_img_size[0], new_img_size[1]);
saveImageToSD(null, thumbfilePath, thb_bitmap, quality);
}
public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
Bitmap newbmp = null;
if (bitmap != null) {
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);
newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
}
return newbmp;
}
public static Bitmap drawableToBitmap(Drawable drawable) {
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, width, height);
drawable.draw(canvas);
return bitmap;
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
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;
}
public static boolean saveBitmap2file(Bitmap bmp, File file, Bitmap.CompressFormat format, int quality) {
if (file.isFile()) file.delete();
OutputStream stream = null;
try {
stream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
return false;
}
return bmp.compress(format, quality, stream);
}
}
以上僅列出部分常用方法,完整的 ImageUtils 還包含倒影圖、圖片類型判斷、URI 轉絕對路徑、相機解析度排序等,可依專案需求裁剪使用。
Android LayoutInflater 布局服務詳解
Android LayoutInflater 布局服務詳解LayoutInflater 是 Android 中常用的系統服務,主要用於將 XML 布局文件實例化為 Vie
Android GUI 系統之 SurfaceFlinger(五):Vsync 與合成流程解析
Android GUI 系統之 SurfaceFlinger(五):Vsync 與合成流程解析 9. Vsync 第二部分 上一篇提到,視圖的刷新需要經過許多步驟: vo
Android 端實戰:一步步配置極光推送 JPush
Android 端配置極光推送全流程 因為業務上的需要,Android 客戶端得加上推送功能。專案一開始用的是百度推送,但小提醒號碼有時收不到,後來乾脆換成極光推送。極光
ListView 與 Adapter 完全解析:三種適配器的取捨與實作
ListView 是 Android 最經典的列表控制項。它本身只負責「怎麼擺」,資料從哪來、每一列長什麼樣,全交由 Adapter 決定。把 Adapter 搞懂,Li