811a5a4a |
1 | package org.openintents.filemanager.util;\r |
2 | \r |
3 | import android.graphics.Bitmap;\r |
4 | import android.graphics.Canvas;\r |
5 | import android.graphics.Matrix;\r |
6 | import android.graphics.drawable.BitmapDrawable;\r |
7 | import android.graphics.drawable.Drawable;\r |
8 | \r |
9 | public final class ImageUtils {\r |
10 | \r |
11 | /**\r |
12 | * Resizes specific a Bitmap with keeping ratio.\r |
13 | */\r |
14 | public static Bitmap resizeBitmap(Bitmap drawable, int desireWidth,\r |
15 | int desireHeight) {\r |
16 | int width = drawable.getWidth();\r |
17 | int height = drawable.getHeight();\r |
18 | \r |
19 | if (0 < width && 0 < height && desireWidth < width\r |
20 | || desireHeight < height) {\r |
21 | // Calculate scale\r |
22 | float scale;\r |
23 | if (width < height) {\r |
24 | scale = (float) desireHeight / (float) height;\r |
25 | if (desireWidth < width * scale) {\r |
26 | scale = (float) desireWidth / (float) width;\r |
27 | }\r |
28 | } else {\r |
29 | scale = (float) desireWidth / (float) width;\r |
30 | }\r |
31 | \r |
32 | // Draw resized image\r |
33 | Matrix matrix = new Matrix();\r |
34 | matrix.postScale(scale, scale);\r |
35 | Bitmap bitmap = Bitmap.createBitmap(drawable, 0, 0, width, height,\r |
36 | matrix, true);\r |
37 | Canvas canvas = new Canvas(bitmap);\r |
38 | canvas.drawBitmap(bitmap, 0, 0, null);\r |
39 | \r |
40 | drawable = bitmap;\r |
41 | }\r |
42 | \r |
43 | return drawable;\r |
44 | }\r |
45 | \r |
46 | /**\r |
47 | * Resizes specific a Drawable with keeping ratio.\r |
48 | */\r |
49 | public static Drawable resizeDrawable(Drawable drawable, int desireWidth,\r |
50 | int desireHeight) {\r |
51 | int width = drawable.getIntrinsicWidth();\r |
52 | int height = drawable.getIntrinsicHeight();\r |
53 | \r |
54 | if (0 < width && 0 < height && desireWidth < width\r |
55 | || desireHeight < height) {\r |
56 | drawable = new BitmapDrawable(resizeBitmap(\r |
57 | ((BitmapDrawable) drawable).getBitmap(), desireWidth,\r |
58 | desireHeight));\r |
59 | }\r |
60 | \r |
61 | return drawable;\r |
62 | }\r |
63 | \r |
64 | }\r |