BitmapUtils.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. */
  20. package com.owncloud.android.utils;
  21. import android.content.res.Resources;
  22. import android.graphics.Bitmap;
  23. import android.graphics.BitmapFactory;
  24. import android.graphics.BitmapFactory.Options;
  25. import android.graphics.Matrix;
  26. import android.media.ExifInterface;
  27. import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
  28. import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
  29. import com.owncloud.android.authentication.AccountUtils;
  30. import com.owncloud.android.lib.common.utils.Log_OC;
  31. import java.io.UnsupportedEncodingException;
  32. import java.math.BigInteger;
  33. import java.security.MessageDigest;
  34. import java.security.NoSuchAlgorithmException;
  35. import java.util.Locale;
  36. /**
  37. * Utility class with methods for decoding Bitmaps.
  38. */
  39. public class BitmapUtils {
  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
  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. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) {
  55. options.inPreferQualityOverSpeed = false;
  56. }
  57. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
  58. options.inMutable = false;
  59. }
  60. // make a false load of the bitmap to get its dimensions
  61. options.inJustDecodeBounds = true;
  62. BitmapFactory.decodeFile(srcPath, options);
  63. // calculate factor to subsample the bitmap
  64. options.inSampleSize = calculateSampleFactor(options, reqWidth, reqHeight);
  65. // decode bitmap with inSampleSize set
  66. options.inJustDecodeBounds = false;
  67. return BitmapFactory.decodeFile(srcPath, options);
  68. }
  69. /**
  70. * Calculates a proper value for options.inSampleSize in order to decode a Bitmap minimizing
  71. * the memory overload and covering a target surface of reqWidth x reqHeight if the original
  72. * image is big enough.
  73. *
  74. * @param options Bitmap decoding options; options.outHeight and options.inHeight should
  75. * be set.
  76. * @param reqWidth Width of the surface where the Bitmap will be drawn on, in pixels.
  77. * @param reqHeight Height of the surface where the Bitmap will be drawn on, in pixels.
  78. * @return The largest inSampleSize value that is a power of 2 and keeps both
  79. * height and width larger than reqWidth and reqHeight.
  80. */
  81. private static int calculateSampleFactor(Options options, int reqWidth, int reqHeight) {
  82. final int height = options.outHeight;
  83. final int width = options.outWidth;
  84. int inSampleSize = 1;
  85. if (height > reqHeight || width > reqWidth) {
  86. final int halfHeight = height / 2;
  87. final int halfWidth = width / 2;
  88. // calculates the largest inSampleSize value (for smallest sample) that is a power of 2 and keeps both
  89. // height and width **larger** than the requested height and width.
  90. while ((halfHeight / inSampleSize) > reqHeight
  91. && (halfWidth / inSampleSize) > reqWidth) {
  92. inSampleSize *= 2;
  93. }
  94. }
  95. return inSampleSize;
  96. }
  97. /**
  98. * Rotate bitmap according to EXIF orientation.
  99. * Cf. http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/
  100. * @param bitmap Bitmap to be rotated
  101. * @param storagePath Path to source file of bitmap. Needed for EXIF information.
  102. * @return correctly EXIF-rotated bitmap
  103. */
  104. public static Bitmap rotateImage(Bitmap bitmap, String storagePath){
  105. Bitmap resultBitmap = bitmap;
  106. try
  107. {
  108. ExifInterface exifInterface = new ExifInterface(storagePath);
  109. int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
  110. Matrix matrix = new Matrix();
  111. // 1: nothing to do
  112. // 2
  113. if (orientation == ExifInterface.ORIENTATION_FLIP_HORIZONTAL)
  114. {
  115. matrix.postScale(-1.0f, 1.0f);
  116. }
  117. // 3
  118. else if (orientation == ExifInterface.ORIENTATION_ROTATE_180)
  119. {
  120. matrix.postRotate(180);
  121. }
  122. // 4
  123. else if (orientation == ExifInterface.ORIENTATION_FLIP_VERTICAL)
  124. {
  125. matrix.postScale(1.0f, -1.0f);
  126. }
  127. // 5
  128. else if (orientation == ExifInterface.ORIENTATION_TRANSPOSE)
  129. {
  130. matrix.postRotate(-90);
  131. matrix.postScale(1.0f, -1.0f);
  132. }
  133. // 6
  134. else if (orientation == ExifInterface.ORIENTATION_ROTATE_90)
  135. {
  136. matrix.postRotate(90);
  137. }
  138. // 7
  139. else if (orientation == ExifInterface.ORIENTATION_TRANSVERSE)
  140. {
  141. matrix.postRotate(90);
  142. matrix.postScale(1.0f, -1.0f);
  143. }
  144. // 8
  145. else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
  146. {
  147. matrix.postRotate(270);
  148. }
  149. // Rotate the bitmap
  150. resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
  151. if (!resultBitmap.equals(bitmap)) {
  152. bitmap.recycle();
  153. }
  154. }
  155. catch (Exception exception)
  156. {
  157. Log_OC.e("BitmapUtil", "Could not rotate the image: " + storagePath);
  158. }
  159. return resultBitmap;
  160. }
  161. /**
  162. * Convert HSL values to a RGB Color.
  163. *
  164. * @param h Hue is specified as degrees in the range 0 - 360.
  165. * @param s Saturation is specified as a percentage in the range 1 - 100.
  166. * @param l Lumanance is specified as a percentage in the range 1 - 100.
  167. * @paran alpha the alpha value between 0 - 1
  168. * adapted from https://svn.codehaus.org/griffon/builders/gfxbuilder/tags/GFXBUILDER_0.2/
  169. * gfxbuilder-core/src/main/com/camick/awt/HSLColor.java
  170. */
  171. @SuppressWarnings("PMD.MethodNamingConventions")
  172. public static int[] HSLtoRGB(float h, float s, float l, float alpha)
  173. {
  174. if (s <0.0f || s > 100.0f)
  175. {
  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. {
  181. String message = "Color parameter outside of expected range - Luminance";
  182. throw new IllegalArgumentException( message );
  183. }
  184. if (alpha <0.0f || alpha > 1.0f)
  185. {
  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 = 0;
  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 accountName The account 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[] calculateRGB(String accountName) throws UnsupportedEncodingException, NoSuchAlgorithmException {
  234. // using adapted algorithm from /core/js/placeholder.js:50
  235. String username = AccountUtils.getAccountUsername(accountName);
  236. byte[] seed = username.getBytes("UTF-8");
  237. MessageDigest md = MessageDigest.getInstance("MD5");
  238. Integer seedMd5Int = String.format(Locale.ROOT, "%032x",
  239. new BigInteger(1, md.digest(seed))).hashCode();
  240. double maxRange = Integer.MAX_VALUE;
  241. float hue = (float) (seedMd5Int / maxRange * 360);
  242. return BitmapUtils.HSLtoRGB(hue, 90.0f, 65.0f, 1.0f);
  243. }
  244. /**
  245. * Returns a new circular bitmap drawable by creating it from a bitmap, setting initial target density based on
  246. * the display metrics of the resources.
  247. *
  248. * @param resources the resources for initial target density
  249. * @param bitmap the original bitmap
  250. * @return the circular bitmap
  251. */
  252. public static RoundedBitmapDrawable bitmapToCircularBitmapDrawable(Resources resources, Bitmap bitmap) {
  253. RoundedBitmapDrawable roundedBitmap = RoundedBitmapDrawableFactory.create(resources, bitmap);
  254. roundedBitmap.setCircular(true);
  255. return roundedBitmap;
  256. }
  257. }