BitmapUtils.java 14 KB

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