BitmapUtils.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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.Matrix;
  25. import android.media.ExifInterface;
  26. import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
  27. import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
  28. import com.owncloud.android.lib.common.utils.Log_OC;
  29. import java.io.UnsupportedEncodingException;
  30. import java.math.BigInteger;
  31. import java.security.MessageDigest;
  32. import java.security.NoSuchAlgorithmException;
  33. import java.util.Locale;
  34. /**
  35. * Utility class with methods for decoding Bitmaps.
  36. */
  37. public class BitmapUtils {
  38. /**
  39. * Decodes a bitmap from a file containing it minimizing the memory use, known that the bitmap
  40. * will be drawn in a surface of reqWidth x reqHeight
  41. *
  42. * @param srcPath Absolute path to the file containing the image.
  43. * @param reqWidth Width of the surface where the Bitmap will be drawn on, in pixels.
  44. * @param reqHeight Height of the surface where the Bitmap will be drawn on, in pixels.
  45. * @return
  46. */
  47. public static Bitmap decodeSampledBitmapFromFile(String srcPath, int reqWidth, int reqHeight) {
  48. // set desired options that will affect the size of the bitmap
  49. final Options options = new Options();
  50. options.inScaled = true;
  51. options.inPurgeable = true;
  52. options.inPreferQualityOverSpeed = false;
  53. options.inMutable = false;
  54. // make a false load of the bitmap to get its dimensions
  55. options.inJustDecodeBounds = true;
  56. BitmapFactory.decodeFile(srcPath, options);
  57. // calculate factor to subsample the bitmap
  58. options.inSampleSize = calculateSampleFactor(options, reqWidth, reqHeight);
  59. // decode bitmap with inSampleSize set
  60. options.inJustDecodeBounds = false;
  61. return BitmapFactory.decodeFile(srcPath, options);
  62. }
  63. /**
  64. * Calculates a proper value for options.inSampleSize in order to decode a Bitmap minimizing
  65. * the memory overload and covering a target surface of reqWidth x reqHeight if the original
  66. * image is big enough.
  67. *
  68. * @param options Bitmap decoding options; options.outHeight and options.inHeight should
  69. * be set.
  70. * @param reqWidth Width of the surface where the Bitmap will be drawn on, in pixels.
  71. * @param reqHeight Height of the surface where the Bitmap will be drawn on, in pixels.
  72. * @return The largest inSampleSize value that is a power of 2 and keeps both
  73. * height and width larger than reqWidth and reqHeight.
  74. */
  75. private static int calculateSampleFactor(Options options, int reqWidth, int reqHeight) {
  76. final int height = options.outHeight;
  77. final int width = options.outWidth;
  78. int inSampleSize = 1;
  79. if (height > reqHeight || width > reqWidth) {
  80. final int halfHeight = height / 2;
  81. final int halfWidth = width / 2;
  82. // calculates the largest inSampleSize value (for smallest sample) that is a power of 2 and keeps both
  83. // height and width **larger** than the requested height and width.
  84. while ((halfHeight / inSampleSize) > reqHeight
  85. && (halfWidth / inSampleSize) > reqWidth) {
  86. inSampleSize *= 2;
  87. }
  88. }
  89. return inSampleSize;
  90. }
  91. /**
  92. * Rotate bitmap according to EXIF orientation.
  93. * Cf. http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/
  94. * @param bitmap Bitmap to be rotated
  95. * @param storagePath Path to source file of bitmap. Needed for EXIF information.
  96. * @return correctly EXIF-rotated bitmap
  97. */
  98. public static Bitmap rotateImage(Bitmap bitmap, String storagePath) {
  99. Bitmap resultBitmap = bitmap;
  100. try {
  101. ExifInterface exifInterface = new ExifInterface(storagePath);
  102. int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
  103. Matrix matrix = new Matrix();
  104. // 1: nothing to do
  105. // 2
  106. if (orientation == ExifInterface.ORIENTATION_FLIP_HORIZONTAL) {
  107. matrix.postScale(-1.0f, 1.0f);
  108. }
  109. // 3
  110. else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
  111. matrix.postRotate(180);
  112. }
  113. // 4
  114. else if (orientation == ExifInterface.ORIENTATION_FLIP_VERTICAL) {
  115. matrix.postScale(1.0f, -1.0f);
  116. }
  117. // 5
  118. else if (orientation == ExifInterface.ORIENTATION_TRANSPOSE) {
  119. matrix.postRotate(-90);
  120. matrix.postScale(1.0f, -1.0f);
  121. }
  122. // 6
  123. else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
  124. matrix.postRotate(90);
  125. }
  126. // 7
  127. else if (orientation == ExifInterface.ORIENTATION_TRANSVERSE) {
  128. matrix.postRotate(90);
  129. matrix.postScale(1.0f, -1.0f);
  130. }
  131. // 8
  132. else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
  133. matrix.postRotate(270);
  134. }
  135. // Rotate the bitmap
  136. resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  137. if (!resultBitmap.equals(bitmap)) {
  138. bitmap.recycle();
  139. }
  140. } catch (Exception exception) {
  141. Log_OC.e("BitmapUtil", "Could not rotate the image: " + storagePath);
  142. }
  143. return resultBitmap;
  144. }
  145. /**
  146. * Convert HSL values to a RGB Color.
  147. *
  148. * @param h Hue is specified as degrees in the range 0 - 360.
  149. * @param s Saturation is specified as a percentage in the range 1 - 100.
  150. * @param l Lumanance is specified as a percentage in the range 1 - 100.
  151. * @paran alpha the alpha value between 0 - 1
  152. * adapted from https://svn.codehaus.org/griffon/builders/gfxbuilder/tags/GFXBUILDER_0.2/
  153. * gfxbuilder-core/src/main/com/camick/awt/HSLColor.java
  154. */
  155. @SuppressWarnings("PMD.MethodNamingConventions")
  156. public static int[] HSLtoRGB(float h, float s, float l, float alpha) {
  157. if (s < 0.0f || s > 100.0f) {
  158. String message = "Color parameter outside of expected range - Saturation";
  159. throw new IllegalArgumentException(message);
  160. }
  161. if (l < 0.0f || l > 100.0f) {
  162. String message = "Color parameter outside of expected range - Luminance";
  163. throw new IllegalArgumentException(message);
  164. }
  165. if (alpha < 0.0f || alpha > 1.0f) {
  166. String message = "Color parameter outside of expected range - Alpha";
  167. throw new IllegalArgumentException(message);
  168. }
  169. // Formula needs all values between 0 - 1.
  170. h = h % 360.0f;
  171. h /= 360f;
  172. s /= 100f;
  173. l /= 100f;
  174. float q = 0;
  175. if (l < 0.5) {
  176. q = l * (1 + s);
  177. } else {
  178. q = (l + s) - (s * l);
  179. }
  180. float p = 2 * l - q;
  181. int r = Math.round(Math.max(0, HueToRGB(p, q, h + (1.0f / 3.0f)) * 256));
  182. int g = Math.round(Math.max(0, HueToRGB(p, q, h) * 256));
  183. int b = Math.round(Math.max(0, HueToRGB(p, q, h - (1.0f / 3.0f)) * 256));
  184. return new int[]{r, g, b};
  185. }
  186. @SuppressWarnings("PMD.MethodNamingConventions")
  187. private static float HueToRGB(float p, float q, float h) {
  188. if (h < 0) {
  189. h += 1;
  190. }
  191. if (h > 1) {
  192. h -= 1;
  193. }
  194. if (6 * h < 1) {
  195. return p + ((q - p) * 6 * h);
  196. }
  197. if (2 * h < 1) {
  198. return q;
  199. }
  200. if (3 * h < 2) {
  201. return p + ((q - p) * 6 * ((2.0f / 3.0f) - h));
  202. }
  203. return p;
  204. }
  205. /**
  206. * calculates the RGB value based on a given account name.
  207. *
  208. * @param name The name
  209. * @return corresponding RGB color
  210. * @throws UnsupportedEncodingException if the charset is not supported
  211. * @throws NoSuchAlgorithmException if the specified algorithm is not available
  212. */
  213. public static int[] calculateRGB(String name) throws UnsupportedEncodingException, NoSuchAlgorithmException {
  214. // using adapted algorithm from /core/js/placeholder.js:50
  215. byte[] seed = name.getBytes("UTF-8");
  216. MessageDigest md = MessageDigest.getInstance("MD5");
  217. Integer seedMd5Int = String.format(Locale.ROOT, "%032x",
  218. new BigInteger(1, md.digest(seed))).hashCode();
  219. double maxRange = Integer.MAX_VALUE;
  220. float hue = (float) (seedMd5Int / maxRange * 360);
  221. return BitmapUtils.HSLtoRGB(hue, 90.0f, 65.0f, 1.0f);
  222. }
  223. /**
  224. * Returns a new circular bitmap drawable by creating it from a bitmap, setting initial target density based on
  225. * the display metrics of the resources.
  226. *
  227. * @param resources the resources for initial target density
  228. * @param bitmap the original bitmap
  229. * @return the circular bitmap
  230. */
  231. public static RoundedBitmapDrawable bitmapToCircularBitmapDrawable(Resources resources, Bitmap bitmap) {
  232. RoundedBitmapDrawable roundedBitmap = RoundedBitmapDrawableFactory.create(resources, bitmap);
  233. roundedBitmap.setCircular(true);
  234. return roundedBitmap;
  235. }
  236. }