BitmapUtils.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * Copyright (C) 2015 ownCloud Inc.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.owncloud.android.utils;
  20. import android.content.res.Resources;
  21. import android.graphics.Bitmap;
  22. import android.graphics.BitmapFactory;
  23. import android.graphics.BitmapFactory.Options;
  24. import android.graphics.Canvas;
  25. import android.graphics.Matrix;
  26. import android.graphics.drawable.BitmapDrawable;
  27. import android.graphics.drawable.Drawable;
  28. import android.support.media.ExifInterface;
  29. import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
  30. import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
  31. import com.owncloud.android.lib.common.utils.Log_OC;
  32. import org.apache.commons.codec.binary.Hex;
  33. import java.io.UnsupportedEncodingException;
  34. import java.security.MessageDigest;
  35. import java.security.NoSuchAlgorithmException;
  36. import java.util.Locale;
  37. /**
  38. * Utility class with methods for decoding Bitmaps.
  39. */
  40. public class BitmapUtils {
  41. public static final String TAG = BitmapUtils.class.getSimpleName();
  42. /**
  43. * Decodes a bitmap from a file containing it minimizing the memory use, known that the bitmap
  44. * will be drawn in a surface of reqWidth x reqHeight
  45. *
  46. * @param srcPath Absolute path to the file containing the image.
  47. * @param reqWidth Width of the surface where the Bitmap will be drawn on, in pixels.
  48. * @param reqHeight Height of the surface where the Bitmap will be drawn on, in pixels.
  49. * @return decoded bitmap
  50. */
  51. public static Bitmap decodeSampledBitmapFromFile(String srcPath, int reqWidth, int reqHeight) {
  52. // set desired options that will affect the size of the bitmap
  53. final Options options = new Options();
  54. options.inScaled = true;
  55. options.inPurgeable = true;
  56. options.inPreferQualityOverSpeed = false;
  57. options.inMutable = false;
  58. // make a false load of the bitmap to get its dimensions
  59. options.inJustDecodeBounds = true;
  60. BitmapFactory.decodeFile(srcPath, options);
  61. // calculate factor to subsample the bitmap
  62. options.inSampleSize = calculateSampleFactor(options, reqWidth, reqHeight);
  63. // decode bitmap with inSampleSize set
  64. options.inJustDecodeBounds = false;
  65. return BitmapFactory.decodeFile(srcPath, options);
  66. }
  67. /**
  68. * Calculates a proper value for options.inSampleSize in order to decode a Bitmap minimizing
  69. * the memory overload and covering a target surface of reqWidth x reqHeight if the original
  70. * image is big enough.
  71. *
  72. * @param options Bitmap decoding options; options.outHeight and options.inHeight should
  73. * be set.
  74. * @param reqWidth Width of the surface where the Bitmap will be drawn on, in pixels.
  75. * @param reqHeight Height of the surface where the Bitmap will be drawn on, in pixels.
  76. * @return The largest inSampleSize value that is a power of 2 and keeps both
  77. * height and width larger than reqWidth and reqHeight.
  78. */
  79. private static int calculateSampleFactor(Options options, int reqWidth, int reqHeight) {
  80. final int height = options.outHeight;
  81. final int width = options.outWidth;
  82. int inSampleSize = 1;
  83. if (height > reqHeight || width > reqWidth) {
  84. final int halfHeight = height / 2;
  85. final int halfWidth = width / 2;
  86. // calculates the largest inSampleSize value (for smallest sample) that is a power of 2 and keeps both
  87. // height and width **larger** than the requested height and width.
  88. while ((halfHeight / inSampleSize) > reqHeight
  89. && (halfWidth / inSampleSize) > reqWidth) {
  90. inSampleSize *= 2;
  91. }
  92. }
  93. return inSampleSize;
  94. }
  95. /**
  96. * scales a given bitmap depending on the given size parameters.
  97. *
  98. * @param bitmap the bitmap to be scaled
  99. * @param px the target pixel size
  100. * @param width the width
  101. * @param height the height
  102. * @param max the max(height, width)
  103. * @return the scaled bitmap
  104. */
  105. public static Bitmap scaleBitmap(Bitmap bitmap, float px, int width, int height, int max) {
  106. float scale = px / max;
  107. int w = Math.round(scale * width);
  108. int h = Math.round(scale * height);
  109. return Bitmap.createScaledBitmap(bitmap, w, h, true);
  110. }
  111. /**
  112. * Rotate bitmap according to EXIF orientation.
  113. * Cf. http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/
  114. * @param bitmap Bitmap to be rotated
  115. * @param storagePath Path to source file of bitmap. Needed for EXIF information.
  116. * @return correctly EXIF-rotated bitmap
  117. */
  118. public static Bitmap rotateImage(Bitmap bitmap, String storagePath) {
  119. Bitmap resultBitmap = bitmap;
  120. try {
  121. ExifInterface exifInterface = new ExifInterface(storagePath);
  122. int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
  123. Matrix matrix = new Matrix();
  124. // 1: nothing to do
  125. // 2
  126. if (orientation == ExifInterface.ORIENTATION_FLIP_HORIZONTAL) {
  127. matrix.postScale(-1.0f, 1.0f);
  128. }
  129. // 3
  130. else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
  131. matrix.postRotate(180);
  132. }
  133. // 4
  134. else if (orientation == ExifInterface.ORIENTATION_FLIP_VERTICAL) {
  135. matrix.postScale(1.0f, -1.0f);
  136. }
  137. // 5
  138. else if (orientation == ExifInterface.ORIENTATION_TRANSPOSE) {
  139. matrix.postRotate(-90);
  140. matrix.postScale(1.0f, -1.0f);
  141. }
  142. // 6
  143. else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
  144. matrix.postRotate(90);
  145. }
  146. // 7
  147. else if (orientation == ExifInterface.ORIENTATION_TRANSVERSE) {
  148. matrix.postRotate(90);
  149. matrix.postScale(1.0f, -1.0f);
  150. }
  151. // 8
  152. else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
  153. matrix.postRotate(270);
  154. }
  155. // Rotate the bitmap
  156. resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  157. if (!resultBitmap.equals(bitmap)) {
  158. bitmap.recycle();
  159. }
  160. } catch (Exception exception) {
  161. Log_OC.e("BitmapUtil", "Could not rotate the image: " + storagePath);
  162. }
  163. return resultBitmap;
  164. }
  165. /**
  166. * Convert HSL values to a RGB Color.
  167. *
  168. * @param h Hue is specified as degrees in the range 0 - 360.
  169. * @param s Saturation is specified as a percentage in the range 1 - 100.
  170. * @param l Luminance is specified as a percentage in the range 1 - 100.
  171. * @param alpha the alpha value between 0 - 1
  172. * adapted from https://svn.codehaus.org/griffon/builders/gfxbuilder/tags/GFXBUILDER_0.2/
  173. * gfxbuilder-core/src/main/com/camick/awt/HSLColor.java
  174. */
  175. @SuppressWarnings("PMD.MethodNamingConventions")
  176. public static int[] HSLtoRGB(float h, float s, float l, float alpha) {
  177. if (s < 0.0f || s > 100.0f) {
  178. String message = "Color parameter outside of expected range - Saturation";
  179. throw new IllegalArgumentException(message);
  180. }
  181. if (l < 0.0f || l > 100.0f) {
  182. String message = "Color parameter outside of expected range - Luminance";
  183. throw new IllegalArgumentException(message);
  184. }
  185. if (alpha < 0.0f || alpha > 1.0f) {
  186. String message = "Color parameter outside of expected range - Alpha";
  187. throw new IllegalArgumentException(message);
  188. }
  189. // Formula needs all values between 0 - 1.
  190. h = h % 360.0f;
  191. h /= 360f;
  192. s /= 100f;
  193. l /= 100f;
  194. float q;
  195. if (l < 0.5) {
  196. q = l * (1 + s);
  197. } else {
  198. q = (l + s) - (s * l);
  199. }
  200. float p = 2 * l - q;
  201. int r = Math.round(Math.max(0, HueToRGB(p, q, h + (1.0f / 3.0f)) * 256));
  202. int g = Math.round(Math.max(0, HueToRGB(p, q, h) * 256));
  203. int b = Math.round(Math.max(0, HueToRGB(p, q, h - (1.0f / 3.0f)) * 256));
  204. return new int[]{r, g, b};
  205. }
  206. @SuppressWarnings("PMD.MethodNamingConventions")
  207. private static float HueToRGB(float p, float q, float h) {
  208. if (h < 0) {
  209. h += 1;
  210. }
  211. if (h > 1) {
  212. h -= 1;
  213. }
  214. if (6 * h < 1) {
  215. return p + ((q - p) * 6 * h);
  216. }
  217. if (2 * h < 1) {
  218. return q;
  219. }
  220. if (3 * h < 2) {
  221. return p + ((q - p) * 6 * ((2.0f / 3.0f) - h));
  222. }
  223. return p;
  224. }
  225. /**
  226. * calculates the RGB value based on a given account name.
  227. *
  228. * @param name The name
  229. * @return corresponding RGB color
  230. * @throws UnsupportedEncodingException if the charset is not supported
  231. * @throws NoSuchAlgorithmException if the specified algorithm is not available
  232. */
  233. public static int[] calculateHSL(String name) throws UnsupportedEncodingException, NoSuchAlgorithmException {
  234. // using adapted algorithm from https://github.com/nextcloud/server/blob/master/core/js/placeholder.js#L126
  235. String[] result = new String[]{"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"};
  236. double[] rgb = new double[]{0, 0, 0};
  237. int sat = 70;
  238. int lum = 68;
  239. int modulo = 16;
  240. String hash = name.toLowerCase(Locale.ROOT).replaceAll("[^0-9a-f]", "");
  241. if (!hash.matches("^[0-9a-f]{32}")) {
  242. hash = md5(hash);
  243. }
  244. // Splitting evenly the string
  245. for (int i = 0; i < hash.length(); i++) {
  246. result[i % modulo] = result[i % modulo] + String.valueOf(Integer.parseInt(hash.substring(i, i + 1), 16));
  247. }
  248. // Converting our data into a usable rgb format
  249. // Start at 1 because 16%3=1 but 15%3=0 and makes the repartition even
  250. for (int count = 1; count < modulo; count++) {
  251. rgb[count % 3] += (Integer.parseInt(result[count]));
  252. }
  253. // Reduce values bigger than rgb requirements
  254. rgb[0] = rgb[0] % 255;
  255. rgb[1] = rgb[1] % 255;
  256. rgb[2] = rgb[2] % 255;
  257. double[] hsl = rgbToHsl(rgb[0], rgb[1], rgb[2]);
  258. // Classic formula to check the brightness for our eye
  259. // If too bright, lower the sat
  260. double bright = Math.sqrt(0.299 * Math.pow(rgb[0], 2) + 0.587 * Math.pow(rgb[1], 2) + 0.114
  261. * Math.pow(rgb[2], 2));
  262. if (bright >= 200) {
  263. sat = 60;
  264. }
  265. return new int[]{(int) (hsl[0] * 360), sat, lum};
  266. }
  267. private static double[] rgbToHsl(double rUntrimmed, double gUntrimmed, double bUntrimmed) {
  268. double r = rUntrimmed / 255;
  269. double g = gUntrimmed / 255;
  270. double b = bUntrimmed / 255;
  271. double max = Math.max(r, Math.max(g, b));
  272. double min = Math.min(r, Math.min(g, b));
  273. double h = (max + min) / 2;
  274. double s;
  275. double l = (max + min) / 2;
  276. if (max == min) {
  277. h = s = 0; // achromatic
  278. } else {
  279. double d = max - min;
  280. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  281. if (max == r) {
  282. h = (g - b) / d + (g < b ? 6 : 0);
  283. } else if (max == g) {
  284. h = (b - r) / d + 2;
  285. } else if (max == b) {
  286. h = (r - g) / d + 4;
  287. }
  288. h /= 6;
  289. }
  290. double[] hsl = new double[]{0.0, 0.0, 0.0};
  291. hsl[0] = h;
  292. hsl[1] = s;
  293. hsl[2] = l;
  294. return hsl;
  295. }
  296. public static String md5(String string) {
  297. try {
  298. MessageDigest md5 = MessageDigest.getInstance("MD5");
  299. md5.update(string.getBytes());
  300. return new String(Hex.encodeHex(md5.digest()));
  301. } catch (Exception e) {
  302. Log_OC.e(TAG, e.getMessage());
  303. }
  304. return "";
  305. }
  306. /**
  307. * Returns a new circular bitmap drawable by creating it from a bitmap, setting initial target density based on
  308. * the display metrics of the resources.
  309. *
  310. * @param resources the resources for initial target density
  311. * @param bitmap the original bitmap
  312. * @return the circular bitmap
  313. */
  314. public static RoundedBitmapDrawable bitmapToCircularBitmapDrawable(Resources resources, Bitmap bitmap) {
  315. RoundedBitmapDrawable roundedBitmap = RoundedBitmapDrawableFactory.create(resources, bitmap);
  316. roundedBitmap.setCircular(true);
  317. return roundedBitmap;
  318. }
  319. public static Bitmap drawableToBitmap(Drawable drawable) {
  320. Bitmap bitmap;
  321. if (drawable instanceof BitmapDrawable) {
  322. BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
  323. if (bitmapDrawable.getBitmap() != null) {
  324. return bitmapDrawable.getBitmap();
  325. }
  326. }
  327. if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
  328. bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
  329. } else {
  330. bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
  331. Bitmap.Config.ARGB_8888);
  332. }
  333. Canvas canvas = new Canvas(bitmap);
  334. drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
  335. drawable.draw(canvas);
  336. return bitmap;
  337. }
  338. }