BitmapUtils.java 14 KB

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