ImageUtils.java 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374
  1. package com.cooleshow.base.utils;
  2. import android.Manifest;
  3. import android.content.ContentValues;
  4. import android.content.res.Resources;
  5. import android.graphics.Bitmap;
  6. import android.graphics.Bitmap.CompressFormat;
  7. import android.graphics.BitmapFactory;
  8. import android.graphics.BitmapShader;
  9. import android.graphics.Canvas;
  10. import android.graphics.Color;
  11. import android.graphics.ColorMatrix;
  12. import android.graphics.ColorMatrixColorFilter;
  13. import android.graphics.LinearGradient;
  14. import android.graphics.Matrix;
  15. import android.graphics.Paint;
  16. import android.graphics.Path;
  17. import android.graphics.PixelFormat;
  18. import android.graphics.PorterDuff;
  19. import android.graphics.PorterDuffColorFilter;
  20. import android.graphics.PorterDuffXfermode;
  21. import android.graphics.Rect;
  22. import android.graphics.RectF;
  23. import android.graphics.Shader;
  24. import android.graphics.drawable.BitmapDrawable;
  25. import android.graphics.drawable.Drawable;
  26. import android.media.ExifInterface;
  27. import android.net.Uri;
  28. import android.os.Build;
  29. import android.os.Environment;
  30. import android.provider.MediaStore;
  31. import android.renderscript.Allocation;
  32. import android.renderscript.Element;
  33. import android.renderscript.RenderScript;
  34. import android.renderscript.ScriptIntrinsicBlur;
  35. import android.text.TextUtils;
  36. import android.util.Log;
  37. import android.view.View;
  38. import java.io.BufferedOutputStream;
  39. import java.io.ByteArrayOutputStream;
  40. import java.io.File;
  41. import java.io.FileDescriptor;
  42. import java.io.FileInputStream;
  43. import java.io.FileOutputStream;
  44. import java.io.IOException;
  45. import java.io.InputStream;
  46. import java.io.OutputStream;
  47. import androidx.annotation.ColorInt;
  48. import androidx.annotation.DrawableRes;
  49. import androidx.annotation.FloatRange;
  50. import androidx.annotation.IntRange;
  51. import androidx.annotation.NonNull;
  52. import androidx.annotation.Nullable;
  53. import androidx.annotation.RequiresApi;
  54. import androidx.core.content.ContextCompat;
  55. /**
  56. * <pre>
  57. * author: Blankj
  58. * blog : http://blankj.com
  59. * time : 2016/08/12
  60. * desc : utils about image
  61. * </pre>
  62. */
  63. public final class ImageUtils {
  64. private ImageUtils() {
  65. throw new UnsupportedOperationException("u can't instantiate me...");
  66. }
  67. /**
  68. * Bitmap to bytes.
  69. *
  70. * @param bitmap The bitmap.
  71. * @return bytes
  72. */
  73. public static byte[] bitmap2Bytes(final Bitmap bitmap) {
  74. return bitmap2Bytes(bitmap, CompressFormat.PNG, 100);
  75. }
  76. /**
  77. * Bitmap to bytes.
  78. *
  79. * @param bitmap The bitmap.
  80. * @param format The format of bitmap.
  81. * @param quality The quality.
  82. * @return bytes
  83. */
  84. public static byte[] bitmap2Bytes(@Nullable final Bitmap bitmap, @NonNull final CompressFormat format, int quality) {
  85. if (bitmap == null) return null;
  86. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  87. bitmap.compress(format, quality, baos);
  88. return baos.toByteArray();
  89. }
  90. /**
  91. * Bytes to bitmap.
  92. *
  93. * @param bytes The bytes.
  94. * @return bitmap
  95. */
  96. public static Bitmap bytes2Bitmap(@Nullable final byte[] bytes) {
  97. return (bytes == null || bytes.length == 0)
  98. ? null
  99. : BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
  100. }
  101. /**
  102. * Drawable to bitmap.
  103. *
  104. * @param drawable The drawable.
  105. * @return bitmap
  106. */
  107. public static Bitmap drawable2Bitmap(@Nullable final Drawable drawable) {
  108. if (drawable == null) return null;
  109. if (drawable instanceof BitmapDrawable) {
  110. BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
  111. if (bitmapDrawable.getBitmap() != null) {
  112. return bitmapDrawable.getBitmap();
  113. }
  114. }
  115. Bitmap bitmap;
  116. if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
  117. bitmap = Bitmap.createBitmap(1, 1,
  118. drawable.getOpacity() != PixelFormat.OPAQUE
  119. ? Bitmap.Config.ARGB_8888
  120. : Bitmap.Config.RGB_565);
  121. } else {
  122. bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
  123. drawable.getIntrinsicHeight(),
  124. drawable.getOpacity() != PixelFormat.OPAQUE
  125. ? Bitmap.Config.ARGB_8888
  126. : Bitmap.Config.RGB_565);
  127. }
  128. Canvas canvas = new Canvas(bitmap);
  129. drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
  130. drawable.draw(canvas);
  131. return bitmap;
  132. }
  133. /**
  134. * Bitmap to drawable.
  135. *
  136. * @param bitmap The bitmap.
  137. * @return drawable
  138. */
  139. public static Drawable bitmap2Drawable(@Nullable final Bitmap bitmap) {
  140. return bitmap == null ? null : new BitmapDrawable(Utils.getApp().getResources(), bitmap);
  141. }
  142. /**
  143. * Drawable to bytes.
  144. *
  145. * @param drawable The drawable.
  146. * @return bytes
  147. */
  148. public static byte[] drawable2Bytes(@Nullable final Drawable drawable) {
  149. return drawable == null ? null : bitmap2Bytes(drawable2Bitmap(drawable));
  150. }
  151. /**
  152. * Drawable to bytes.
  153. *
  154. * @param drawable The drawable.
  155. * @param format The format of bitmap.
  156. * @return bytes
  157. */
  158. public static byte[] drawable2Bytes(final Drawable drawable, final CompressFormat format, int quality) {
  159. return drawable == null ? null : bitmap2Bytes(drawable2Bitmap(drawable), format, quality);
  160. }
  161. /**
  162. * Bytes to drawable.
  163. *
  164. * @param bytes The bytes.
  165. * @return drawable
  166. */
  167. public static Drawable bytes2Drawable(final byte[] bytes) {
  168. return bitmap2Drawable(bytes2Bitmap(bytes));
  169. }
  170. /**
  171. * View to bitmap.
  172. *
  173. * @param view The view.
  174. * @return bitmap
  175. */
  176. public static Bitmap view2Bitmap(final View view) {
  177. if (view == null) return null;
  178. boolean drawingCacheEnabled = view.isDrawingCacheEnabled();
  179. boolean willNotCacheDrawing = view.willNotCacheDrawing();
  180. view.setDrawingCacheEnabled(true);
  181. view.setWillNotCacheDrawing(false);
  182. Bitmap drawingCache = view.getDrawingCache();
  183. Bitmap bitmap;
  184. if (null == drawingCache || drawingCache.isRecycled()) {
  185. view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
  186. View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
  187. view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
  188. view.buildDrawingCache();
  189. drawingCache = view.getDrawingCache();
  190. if (null == drawingCache || drawingCache.isRecycled()) {
  191. bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.RGB_565);
  192. Canvas canvas = new Canvas(bitmap);
  193. view.draw(canvas);
  194. } else {
  195. bitmap = Bitmap.createBitmap(drawingCache);
  196. }
  197. } else {
  198. bitmap = Bitmap.createBitmap(drawingCache);
  199. }
  200. view.setWillNotCacheDrawing(willNotCacheDrawing);
  201. view.setDrawingCacheEnabled(drawingCacheEnabled);
  202. return bitmap;
  203. }
  204. /**
  205. * Return bitmap.
  206. *
  207. * @param file The file.
  208. * @return bitmap
  209. */
  210. public static Bitmap getBitmap(final File file) {
  211. if (file == null) return null;
  212. return BitmapFactory.decodeFile(file.getAbsolutePath());
  213. }
  214. /**
  215. * Return bitmap.
  216. *
  217. * @param file The file.
  218. * @param maxWidth The maximum width.
  219. * @param maxHeight The maximum height.
  220. * @return bitmap
  221. */
  222. public static Bitmap getBitmap(final File file, final int maxWidth, final int maxHeight) {
  223. if (file == null) return null;
  224. BitmapFactory.Options options = new BitmapFactory.Options();
  225. options.inJustDecodeBounds = true;
  226. BitmapFactory.decodeFile(file.getAbsolutePath(), options);
  227. options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
  228. options.inJustDecodeBounds = false;
  229. return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
  230. }
  231. /**
  232. * Return bitmap.
  233. *
  234. * @param filePath The path of file.
  235. * @return bitmap
  236. */
  237. public static Bitmap getBitmap(final String filePath) {
  238. if (UtilsBridge.isSpace(filePath)) return null;
  239. return BitmapFactory.decodeFile(filePath);
  240. }
  241. /**
  242. * Return bitmap.
  243. *
  244. * @param filePath The path of file.
  245. * @param maxWidth The maximum width.
  246. * @param maxHeight The maximum height.
  247. * @return bitmap
  248. */
  249. public static Bitmap getBitmap(final String filePath, final int maxWidth, final int maxHeight) {
  250. if (UtilsBridge.isSpace(filePath)) return null;
  251. BitmapFactory.Options options = new BitmapFactory.Options();
  252. options.inJustDecodeBounds = true;
  253. BitmapFactory.decodeFile(filePath, options);
  254. options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
  255. options.inJustDecodeBounds = false;
  256. return BitmapFactory.decodeFile(filePath, options);
  257. }
  258. /**
  259. * Return bitmap.
  260. *
  261. * @param is The input stream.
  262. * @return bitmap
  263. */
  264. public static Bitmap getBitmap(final InputStream is) {
  265. if (is == null) return null;
  266. return BitmapFactory.decodeStream(is);
  267. }
  268. /**
  269. * Return bitmap.
  270. *
  271. * @param is The input stream.
  272. * @param maxWidth The maximum width.
  273. * @param maxHeight The maximum height.
  274. * @return bitmap
  275. */
  276. public static Bitmap getBitmap(final InputStream is, final int maxWidth, final int maxHeight) {
  277. if (is == null) return null;
  278. BitmapFactory.Options options = new BitmapFactory.Options();
  279. options.inJustDecodeBounds = true;
  280. BitmapFactory.decodeStream(is, null, options);
  281. options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
  282. options.inJustDecodeBounds = false;
  283. return BitmapFactory.decodeStream(is, null, options);
  284. }
  285. /**
  286. * Return bitmap.
  287. *
  288. * @param data The data.
  289. * @param offset The offset.
  290. * @return bitmap
  291. */
  292. public static Bitmap getBitmap(final byte[] data, final int offset) {
  293. if (data.length == 0) return null;
  294. return BitmapFactory.decodeByteArray(data, offset, data.length);
  295. }
  296. /**
  297. * Return bitmap.
  298. *
  299. * @param data The data.
  300. * @param offset The offset.
  301. * @param maxWidth The maximum width.
  302. * @param maxHeight The maximum height.
  303. * @return bitmap
  304. */
  305. public static Bitmap getBitmap(final byte[] data,
  306. final int offset,
  307. final int maxWidth,
  308. final int maxHeight) {
  309. if (data.length == 0) return null;
  310. BitmapFactory.Options options = new BitmapFactory.Options();
  311. options.inJustDecodeBounds = true;
  312. BitmapFactory.decodeByteArray(data, offset, data.length, options);
  313. options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
  314. options.inJustDecodeBounds = false;
  315. return BitmapFactory.decodeByteArray(data, offset, data.length, options);
  316. }
  317. /**
  318. * Return bitmap.
  319. *
  320. * @param resId The resource id.
  321. * @return bitmap
  322. */
  323. public static Bitmap getBitmap(@DrawableRes final int resId) {
  324. Drawable drawable = ContextCompat.getDrawable(Utils.getApp(), resId);
  325. if (drawable == null) {
  326. return null;
  327. }
  328. Canvas canvas = new Canvas();
  329. Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
  330. drawable.getIntrinsicHeight(),
  331. Bitmap.Config.ARGB_8888);
  332. canvas.setBitmap(bitmap);
  333. drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
  334. drawable.draw(canvas);
  335. return bitmap;
  336. }
  337. /**
  338. * Return bitmap.
  339. *
  340. * @param resId The resource id.
  341. * @param maxWidth The maximum width.
  342. * @param maxHeight The maximum height.
  343. * @return bitmap
  344. */
  345. public static Bitmap getBitmap(@DrawableRes final int resId,
  346. final int maxWidth,
  347. final int maxHeight) {
  348. BitmapFactory.Options options = new BitmapFactory.Options();
  349. final Resources resources = Utils.getApp().getResources();
  350. options.inJustDecodeBounds = true;
  351. BitmapFactory.decodeResource(resources, resId, options);
  352. options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
  353. options.inJustDecodeBounds = false;
  354. return BitmapFactory.decodeResource(resources, resId, options);
  355. }
  356. /**
  357. * Return bitmap.
  358. *
  359. * @param fd The file descriptor.
  360. * @return bitmap
  361. */
  362. public static Bitmap getBitmap(final FileDescriptor fd) {
  363. if (fd == null) return null;
  364. return BitmapFactory.decodeFileDescriptor(fd);
  365. }
  366. /**
  367. * Return bitmap.
  368. *
  369. * @param fd The file descriptor
  370. * @param maxWidth The maximum width.
  371. * @param maxHeight The maximum height.
  372. * @return bitmap
  373. */
  374. public static Bitmap getBitmap(final FileDescriptor fd,
  375. final int maxWidth,
  376. final int maxHeight) {
  377. if (fd == null) return null;
  378. BitmapFactory.Options options = new BitmapFactory.Options();
  379. options.inJustDecodeBounds = true;
  380. BitmapFactory.decodeFileDescriptor(fd, null, options);
  381. options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
  382. options.inJustDecodeBounds = false;
  383. return BitmapFactory.decodeFileDescriptor(fd, null, options);
  384. }
  385. /**
  386. * Return the bitmap with the specified color.
  387. *
  388. * @param src The source of bitmap.
  389. * @param color The color.
  390. * @return the bitmap with the specified color
  391. */
  392. public static Bitmap drawColor(@NonNull final Bitmap src, @ColorInt final int color) {
  393. return drawColor(src, color, false);
  394. }
  395. /**
  396. * Return the bitmap with the specified color.
  397. *
  398. * @param src The source of bitmap.
  399. * @param color The color.
  400. * @param recycle True to recycle the source of bitmap, false otherwise.
  401. * @return the bitmap with the specified color
  402. */
  403. public static Bitmap drawColor(@NonNull final Bitmap src,
  404. @ColorInt final int color,
  405. final boolean recycle) {
  406. if (isEmptyBitmap(src)) return null;
  407. Bitmap ret = recycle ? src : src.copy(src.getConfig(), true);
  408. Canvas canvas = new Canvas(ret);
  409. canvas.drawColor(color, PorterDuff.Mode.DARKEN);
  410. return ret;
  411. }
  412. /**
  413. * Return the scaled bitmap.
  414. *
  415. * @param src The source of bitmap.
  416. * @param newWidth The new width.
  417. * @param newHeight The new height.
  418. * @return the scaled bitmap
  419. */
  420. public static Bitmap scale(final Bitmap src, final int newWidth, final int newHeight) {
  421. return scale(src, newWidth, newHeight, false);
  422. }
  423. /**
  424. * Return the scaled bitmap.
  425. *
  426. * @param src The source of bitmap.
  427. * @param newWidth The new width.
  428. * @param newHeight The new height.
  429. * @param recycle True to recycle the source of bitmap, false otherwise.
  430. * @return the scaled bitmap
  431. */
  432. public static Bitmap scale(final Bitmap src,
  433. final int newWidth,
  434. final int newHeight,
  435. final boolean recycle) {
  436. if (isEmptyBitmap(src)) return null;
  437. Bitmap ret = Bitmap.createScaledBitmap(src, newWidth, newHeight, true);
  438. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  439. return ret;
  440. }
  441. /**
  442. * Return the scaled bitmap
  443. *
  444. * @param src The source of bitmap.
  445. * @param scaleWidth The scale of width.
  446. * @param scaleHeight The scale of height.
  447. * @return the scaled bitmap
  448. */
  449. public static Bitmap scale(final Bitmap src, final float scaleWidth, final float scaleHeight) {
  450. return scale(src, scaleWidth, scaleHeight, false);
  451. }
  452. /**
  453. * Return the scaled bitmap
  454. *
  455. * @param src The source of bitmap.
  456. * @param scaleWidth The scale of width.
  457. * @param scaleHeight The scale of height.
  458. * @param recycle True to recycle the source of bitmap, false otherwise.
  459. * @return the scaled bitmap
  460. */
  461. public static Bitmap scale(final Bitmap src,
  462. final float scaleWidth,
  463. final float scaleHeight,
  464. final boolean recycle) {
  465. if (isEmptyBitmap(src)) return null;
  466. Matrix matrix = new Matrix();
  467. matrix.setScale(scaleWidth, scaleHeight);
  468. Bitmap ret = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
  469. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  470. return ret;
  471. }
  472. /**
  473. * Return the clipped bitmap.
  474. *
  475. * @param src The source of bitmap.
  476. * @param x The x coordinate of the first pixel.
  477. * @param y The y coordinate of the first pixel.
  478. * @param width The width.
  479. * @param height The height.
  480. * @return the clipped bitmap
  481. */
  482. public static Bitmap clip(final Bitmap src,
  483. final int x,
  484. final int y,
  485. final int width,
  486. final int height) {
  487. return clip(src, x, y, width, height, false);
  488. }
  489. /**
  490. * Return the clipped bitmap.
  491. *
  492. * @param src The source of bitmap.
  493. * @param x The x coordinate of the first pixel.
  494. * @param y The y coordinate of the first pixel.
  495. * @param width The width.
  496. * @param height The height.
  497. * @param recycle True to recycle the source of bitmap, false otherwise.
  498. * @return the clipped bitmap
  499. */
  500. public static Bitmap clip(final Bitmap src,
  501. final int x,
  502. final int y,
  503. final int width,
  504. final int height,
  505. final boolean recycle) {
  506. if (isEmptyBitmap(src)) return null;
  507. Bitmap ret = Bitmap.createBitmap(src, x, y, width, height);
  508. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  509. return ret;
  510. }
  511. /**
  512. * Return the skewed bitmap.
  513. *
  514. * @param src The source of bitmap.
  515. * @param kx The skew factor of x.
  516. * @param ky The skew factor of y.
  517. * @return the skewed bitmap
  518. */
  519. public static Bitmap skew(final Bitmap src, final float kx, final float ky) {
  520. return skew(src, kx, ky, 0, 0, false);
  521. }
  522. /**
  523. * Return the skewed bitmap.
  524. *
  525. * @param src The source of bitmap.
  526. * @param kx The skew factor of x.
  527. * @param ky The skew factor of y.
  528. * @param recycle True to recycle the source of bitmap, false otherwise.
  529. * @return the skewed bitmap
  530. */
  531. public static Bitmap skew(final Bitmap src,
  532. final float kx,
  533. final float ky,
  534. final boolean recycle) {
  535. return skew(src, kx, ky, 0, 0, recycle);
  536. }
  537. /**
  538. * Return the skewed bitmap.
  539. *
  540. * @param src The source of bitmap.
  541. * @param kx The skew factor of x.
  542. * @param ky The skew factor of y.
  543. * @param px The x coordinate of the pivot point.
  544. * @param py The y coordinate of the pivot point.
  545. * @return the skewed bitmap
  546. */
  547. public static Bitmap skew(final Bitmap src,
  548. final float kx,
  549. final float ky,
  550. final float px,
  551. final float py) {
  552. return skew(src, kx, ky, px, py, false);
  553. }
  554. /**
  555. * Return the skewed bitmap.
  556. *
  557. * @param src The source of bitmap.
  558. * @param kx The skew factor of x.
  559. * @param ky The skew factor of y.
  560. * @param px The x coordinate of the pivot point.
  561. * @param py The y coordinate of the pivot point.
  562. * @param recycle True to recycle the source of bitmap, false otherwise.
  563. * @return the skewed bitmap
  564. */
  565. public static Bitmap skew(final Bitmap src,
  566. final float kx,
  567. final float ky,
  568. final float px,
  569. final float py,
  570. final boolean recycle) {
  571. if (isEmptyBitmap(src)) return null;
  572. Matrix matrix = new Matrix();
  573. matrix.setSkew(kx, ky, px, py);
  574. Bitmap ret = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
  575. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  576. return ret;
  577. }
  578. /**
  579. * Return the rotated bitmap.
  580. *
  581. * @param src The source of bitmap.
  582. * @param degrees The number of degrees.
  583. * @param px The x coordinate of the pivot point.
  584. * @param py The y coordinate of the pivot point.
  585. * @return the rotated bitmap
  586. */
  587. public static Bitmap rotate(final Bitmap src,
  588. final int degrees,
  589. final float px,
  590. final float py) {
  591. return rotate(src, degrees, px, py, false);
  592. }
  593. /**
  594. * Return the rotated bitmap.
  595. *
  596. * @param src The source of bitmap.
  597. * @param degrees The number of degrees.
  598. * @param px The x coordinate of the pivot point.
  599. * @param py The y coordinate of the pivot point.
  600. * @param recycle True to recycle the source of bitmap, false otherwise.
  601. * @return the rotated bitmap
  602. */
  603. public static Bitmap rotate(final Bitmap src,
  604. final int degrees,
  605. final float px,
  606. final float py,
  607. final boolean recycle) {
  608. if (isEmptyBitmap(src)) return null;
  609. if (degrees == 0) return src;
  610. Matrix matrix = new Matrix();
  611. matrix.setRotate(degrees, px, py);
  612. Bitmap ret = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
  613. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  614. return ret;
  615. }
  616. /**
  617. * Return the rotated degree.
  618. *
  619. * @param filePath The path of file.
  620. * @return the rotated degree
  621. */
  622. public static int getRotateDegree(final String filePath) {
  623. try {
  624. ExifInterface exifInterface = new ExifInterface(filePath);
  625. int orientation = exifInterface.getAttributeInt(
  626. ExifInterface.TAG_ORIENTATION,
  627. ExifInterface.ORIENTATION_NORMAL
  628. );
  629. switch (orientation) {
  630. case ExifInterface.ORIENTATION_ROTATE_90:
  631. return 90;
  632. case ExifInterface.ORIENTATION_ROTATE_180:
  633. return 180;
  634. case ExifInterface.ORIENTATION_ROTATE_270:
  635. return 270;
  636. default:
  637. return 0;
  638. }
  639. } catch (IOException e) {
  640. e.printStackTrace();
  641. return -1;
  642. }
  643. }
  644. /**
  645. * Return the round bitmap.
  646. *
  647. * @param src The source of bitmap.
  648. * @return the round bitmap
  649. */
  650. public static Bitmap toRound(final Bitmap src) {
  651. return toRound(src, 0, 0, false);
  652. }
  653. /**
  654. * Return the round bitmap.
  655. *
  656. * @param src The source of bitmap.
  657. * @param recycle True to recycle the source of bitmap, false otherwise.
  658. * @return the round bitmap
  659. */
  660. public static Bitmap toRound(final Bitmap src, final boolean recycle) {
  661. return toRound(src, 0, 0, recycle);
  662. }
  663. /**
  664. * Return the round bitmap.
  665. *
  666. * @param src The source of bitmap.
  667. * @param borderSize The size of border.
  668. * @param borderColor The color of border.
  669. * @return the round bitmap
  670. */
  671. public static Bitmap toRound(final Bitmap src,
  672. @IntRange(from = 0) int borderSize,
  673. @ColorInt int borderColor) {
  674. return toRound(src, borderSize, borderColor, false);
  675. }
  676. /**
  677. * Return the round bitmap.
  678. *
  679. * @param src The source of bitmap.
  680. * @param recycle True to recycle the source of bitmap, false otherwise.
  681. * @param borderSize The size of border.
  682. * @param borderColor The color of border.
  683. * @return the round bitmap
  684. */
  685. public static Bitmap toRound(final Bitmap src,
  686. @IntRange(from = 0) int borderSize,
  687. @ColorInt int borderColor,
  688. final boolean recycle) {
  689. if (isEmptyBitmap(src)) return null;
  690. int width = src.getWidth();
  691. int height = src.getHeight();
  692. int size = Math.min(width, height);
  693. Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  694. Bitmap ret = Bitmap.createBitmap(width, height, src.getConfig());
  695. float center = size / 2f;
  696. RectF rectF = new RectF(0, 0, width, height);
  697. rectF.inset((width - size) / 2f, (height - size) / 2f);
  698. Matrix matrix = new Matrix();
  699. matrix.setTranslate(rectF.left, rectF.top);
  700. if (width != height) {
  701. matrix.preScale((float) size / width, (float) size / height);
  702. }
  703. BitmapShader shader = new BitmapShader(src, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
  704. shader.setLocalMatrix(matrix);
  705. paint.setShader(shader);
  706. Canvas canvas = new Canvas(ret);
  707. canvas.drawRoundRect(rectF, center, center, paint);
  708. if (borderSize > 0) {
  709. paint.setShader(null);
  710. paint.setColor(borderColor);
  711. paint.setStyle(Paint.Style.STROKE);
  712. paint.setStrokeWidth(borderSize);
  713. float radius = center - borderSize / 2f;
  714. canvas.drawCircle(width / 2f, height / 2f, radius, paint);
  715. }
  716. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  717. return ret;
  718. }
  719. /**
  720. * Return the round corner bitmap.
  721. *
  722. * @param src The source of bitmap.
  723. * @param radius The radius of corner.
  724. * @return the round corner bitmap
  725. */
  726. public static Bitmap toRoundCorner(final Bitmap src, final float radius) {
  727. return toRoundCorner(src, radius, 0, 0, false);
  728. }
  729. /**
  730. * Return the round corner bitmap.
  731. *
  732. * @param src The source of bitmap.
  733. * @param radius The radius of corner.
  734. * @param recycle True to recycle the source of bitmap, false otherwise.
  735. * @return the round corner bitmap
  736. */
  737. public static Bitmap toRoundCorner(final Bitmap src,
  738. final float radius,
  739. final boolean recycle) {
  740. return toRoundCorner(src, radius, 0, 0, recycle);
  741. }
  742. /**
  743. * Return the round corner bitmap.
  744. *
  745. * @param src The source of bitmap.
  746. * @param radius The radius of corner.
  747. * @param borderSize The size of border.
  748. * @param borderColor The color of border.
  749. * @return the round corner bitmap
  750. */
  751. public static Bitmap toRoundCorner(final Bitmap src,
  752. final float radius,
  753. @FloatRange(from = 0) float borderSize,
  754. @ColorInt int borderColor) {
  755. return toRoundCorner(src, radius, borderSize, borderColor, false);
  756. }
  757. /**
  758. * Return the round corner bitmap.
  759. *
  760. * @param src The source of bitmap.
  761. * @param radii Array of 8 values, 4 pairs of [X,Y] radii
  762. * @param borderSize The size of border.
  763. * @param borderColor The color of border.
  764. * @return the round corner bitmap
  765. */
  766. public static Bitmap toRoundCorner(final Bitmap src,
  767. final float[] radii,
  768. @FloatRange(from = 0) float borderSize,
  769. @ColorInt int borderColor) {
  770. return toRoundCorner(src, radii, borderSize, borderColor, false);
  771. }
  772. /**
  773. * Return the round corner bitmap.
  774. *
  775. * @param src The source of bitmap.
  776. * @param radius The radius of corner.
  777. * @param borderSize The size of border.
  778. * @param borderColor The color of border.
  779. * @param recycle True to recycle the source of bitmap, false otherwise.
  780. * @return the round corner bitmap
  781. */
  782. public static Bitmap toRoundCorner(final Bitmap src,
  783. final float radius,
  784. @FloatRange(from = 0) float borderSize,
  785. @ColorInt int borderColor,
  786. final boolean recycle) {
  787. float[] radii = {radius, radius, radius, radius, radius, radius, radius, radius};
  788. return toRoundCorner(src, radii, borderSize, borderColor, recycle);
  789. }
  790. /**
  791. * Return the round corner bitmap.
  792. *
  793. * @param src The source of bitmap.
  794. * @param radii Array of 8 values, 4 pairs of [X,Y] radii
  795. * @param borderSize The size of border.
  796. * @param borderColor The color of border.
  797. * @param recycle True to recycle the source of bitmap, false otherwise.
  798. * @return the round corner bitmap
  799. */
  800. public static Bitmap toRoundCorner(final Bitmap src,
  801. final float[] radii,
  802. @FloatRange(from = 0) float borderSize,
  803. @ColorInt int borderColor,
  804. final boolean recycle) {
  805. if (isEmptyBitmap(src)) return null;
  806. int width = src.getWidth();
  807. int height = src.getHeight();
  808. Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  809. Bitmap ret = Bitmap.createBitmap(width, height, src.getConfig());
  810. BitmapShader shader = new BitmapShader(src, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
  811. paint.setShader(shader);
  812. Canvas canvas = new Canvas(ret);
  813. RectF rectF = new RectF(0, 0, width, height);
  814. float halfBorderSize = borderSize / 2f;
  815. rectF.inset(halfBorderSize, halfBorderSize);
  816. Path path = new Path();
  817. path.addRoundRect(rectF, radii, Path.Direction.CW);
  818. canvas.drawPath(path, paint);
  819. if (borderSize > 0) {
  820. paint.setShader(null);
  821. paint.setColor(borderColor);
  822. paint.setStyle(Paint.Style.STROKE);
  823. paint.setStrokeWidth(borderSize);
  824. paint.setStrokeCap(Paint.Cap.ROUND);
  825. canvas.drawPath(path, paint);
  826. }
  827. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  828. return ret;
  829. }
  830. /**
  831. * Return the round corner bitmap with border.
  832. *
  833. * @param src The source of bitmap.
  834. * @param borderSize The size of border.
  835. * @param color The color of border.
  836. * @param cornerRadius The radius of corner.
  837. * @return the round corner bitmap with border
  838. */
  839. public static Bitmap addCornerBorder(final Bitmap src,
  840. @FloatRange(from = 1) final float borderSize,
  841. @ColorInt final int color,
  842. @FloatRange(from = 0) final float cornerRadius) {
  843. return addBorder(src, borderSize, color, false, cornerRadius, false);
  844. }
  845. /**
  846. * Return the round corner bitmap with border.
  847. *
  848. * @param src The source of bitmap.
  849. * @param borderSize The size of border.
  850. * @param color The color of border.
  851. * @param radii Array of 8 values, 4 pairs of [X,Y] radii
  852. * @return the round corner bitmap with border
  853. */
  854. public static Bitmap addCornerBorder(final Bitmap src,
  855. @FloatRange(from = 1) final float borderSize,
  856. @ColorInt final int color,
  857. final float[] radii) {
  858. return addBorder(src, borderSize, color, false, radii, false);
  859. }
  860. /**
  861. * Return the round corner bitmap with border.
  862. *
  863. * @param src The source of bitmap.
  864. * @param borderSize The size of border.
  865. * @param color The color of border.
  866. * @param radii Array of 8 values, 4 pairs of [X,Y] radii
  867. * @param recycle True to recycle the source of bitmap, false otherwise.
  868. * @return the round corner bitmap with border
  869. */
  870. public static Bitmap addCornerBorder(final Bitmap src,
  871. @FloatRange(from = 1) final float borderSize,
  872. @ColorInt final int color,
  873. final float[] radii,
  874. final boolean recycle) {
  875. return addBorder(src, borderSize, color, false, radii, recycle);
  876. }
  877. /**
  878. * Return the round corner bitmap with border.
  879. *
  880. * @param src The source of bitmap.
  881. * @param borderSize The size of border.
  882. * @param color The color of border.
  883. * @param cornerRadius The radius of corner.
  884. * @param recycle True to recycle the source of bitmap, false otherwise.
  885. * @return the round corner bitmap with border
  886. */
  887. public static Bitmap addCornerBorder(final Bitmap src,
  888. @FloatRange(from = 1) final float borderSize,
  889. @ColorInt final int color,
  890. @FloatRange(from = 0) final float cornerRadius,
  891. final boolean recycle) {
  892. return addBorder(src, borderSize, color, false, cornerRadius, recycle);
  893. }
  894. /**
  895. * Return the round bitmap with border.
  896. *
  897. * @param src The source of bitmap.
  898. * @param borderSize The size of border.
  899. * @param color The color of border.
  900. * @return the round bitmap with border
  901. */
  902. public static Bitmap addCircleBorder(final Bitmap src,
  903. @FloatRange(from = 1) final float borderSize,
  904. @ColorInt final int color) {
  905. return addBorder(src, borderSize, color, true, 0, false);
  906. }
  907. /**
  908. * Return the round bitmap with border.
  909. *
  910. * @param src The source of bitmap.
  911. * @param borderSize The size of border.
  912. * @param color The color of border.
  913. * @param recycle True to recycle the source of bitmap, false otherwise.
  914. * @return the round bitmap with border
  915. */
  916. public static Bitmap addCircleBorder(final Bitmap src,
  917. @FloatRange(from = 1) final float borderSize,
  918. @ColorInt final int color,
  919. final boolean recycle) {
  920. return addBorder(src, borderSize, color, true, 0, recycle);
  921. }
  922. /**
  923. * Return the bitmap with border.
  924. *
  925. * @param src The source of bitmap.
  926. * @param borderSize The size of border.
  927. * @param color The color of border.
  928. * @param isCircle True to draw circle, false to draw corner.
  929. * @param cornerRadius The radius of corner.
  930. * @param recycle True to recycle the source of bitmap, false otherwise.
  931. * @return the bitmap with border
  932. */
  933. private static Bitmap addBorder(final Bitmap src,
  934. @FloatRange(from = 1) final float borderSize,
  935. @ColorInt final int color,
  936. final boolean isCircle,
  937. final float cornerRadius,
  938. final boolean recycle) {
  939. float[] radii = {cornerRadius, cornerRadius, cornerRadius, cornerRadius,
  940. cornerRadius, cornerRadius, cornerRadius, cornerRadius};
  941. return addBorder(src, borderSize, color, isCircle, radii, recycle);
  942. }
  943. /**
  944. * Return the bitmap with border.
  945. *
  946. * @param src The source of bitmap.
  947. * @param borderSize The size of border.
  948. * @param color The color of border.
  949. * @param isCircle True to draw circle, false to draw corner.
  950. * @param radii Array of 8 values, 4 pairs of [X,Y] radii
  951. * @param recycle True to recycle the source of bitmap, false otherwise.
  952. * @return the bitmap with border
  953. */
  954. private static Bitmap addBorder(final Bitmap src,
  955. @FloatRange(from = 1) final float borderSize,
  956. @ColorInt final int color,
  957. final boolean isCircle,
  958. final float[] radii,
  959. final boolean recycle) {
  960. if (isEmptyBitmap(src)) return null;
  961. Bitmap ret = recycle ? src : src.copy(src.getConfig(), true);
  962. int width = ret.getWidth();
  963. int height = ret.getHeight();
  964. Canvas canvas = new Canvas(ret);
  965. Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  966. paint.setColor(color);
  967. paint.setStyle(Paint.Style.STROKE);
  968. paint.setStrokeWidth(borderSize);
  969. if (isCircle) {
  970. float radius = Math.min(width, height) / 2f - borderSize / 2f;
  971. canvas.drawCircle(width / 2f, height / 2f, radius, paint);
  972. } else {
  973. RectF rectF = new RectF(0, 0, width, height);
  974. float halfBorderSize = borderSize / 2f;
  975. rectF.inset(halfBorderSize, halfBorderSize);
  976. Path path = new Path();
  977. path.addRoundRect(rectF, radii, Path.Direction.CW);
  978. canvas.drawPath(path, paint);
  979. }
  980. return ret;
  981. }
  982. /**
  983. * Return the bitmap with reflection.
  984. *
  985. * @param src The source of bitmap.
  986. * @param reflectionHeight The height of reflection.
  987. * @return the bitmap with reflection
  988. */
  989. public static Bitmap addReflection(final Bitmap src, final int reflectionHeight) {
  990. return addReflection(src, reflectionHeight, false);
  991. }
  992. /**
  993. * Return the bitmap with reflection.
  994. *
  995. * @param src The source of bitmap.
  996. * @param reflectionHeight The height of reflection.
  997. * @param recycle True to recycle the source of bitmap, false otherwise.
  998. * @return the bitmap with reflection
  999. */
  1000. public static Bitmap addReflection(final Bitmap src,
  1001. final int reflectionHeight,
  1002. final boolean recycle) {
  1003. if (isEmptyBitmap(src)) return null;
  1004. final int REFLECTION_GAP = 0;
  1005. int srcWidth = src.getWidth();
  1006. int srcHeight = src.getHeight();
  1007. Matrix matrix = new Matrix();
  1008. matrix.preScale(1, -1);
  1009. Bitmap reflectionBitmap = Bitmap.createBitmap(src, 0, srcHeight - reflectionHeight,
  1010. srcWidth, reflectionHeight, matrix, false);
  1011. Bitmap ret = Bitmap.createBitmap(srcWidth, srcHeight + reflectionHeight, src.getConfig());
  1012. Canvas canvas = new Canvas(ret);
  1013. canvas.drawBitmap(src, 0, 0, null);
  1014. canvas.drawBitmap(reflectionBitmap, 0, srcHeight + REFLECTION_GAP, null);
  1015. Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  1016. LinearGradient shader = new LinearGradient(
  1017. 0, srcHeight,
  1018. 0, ret.getHeight() + REFLECTION_GAP,
  1019. 0x70FFFFFF,
  1020. 0x00FFFFFF,
  1021. Shader.TileMode.MIRROR);
  1022. paint.setShader(shader);
  1023. paint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_IN));
  1024. canvas.drawRect(0, srcHeight + REFLECTION_GAP, srcWidth, ret.getHeight(), paint);
  1025. if (!reflectionBitmap.isRecycled()) reflectionBitmap.recycle();
  1026. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  1027. return ret;
  1028. }
  1029. /**
  1030. * Return the bitmap with text watermarking.
  1031. *
  1032. * @param src The source of bitmap.
  1033. * @param content The content of text.
  1034. * @param textSize The size of text.
  1035. * @param color The color of text.
  1036. * @param x The x coordinate of the first pixel.
  1037. * @param y The y coordinate of the first pixel.
  1038. * @return the bitmap with text watermarking
  1039. */
  1040. public static Bitmap addTextWatermark(final Bitmap src,
  1041. final String content,
  1042. final int textSize,
  1043. @ColorInt final int color,
  1044. final float x,
  1045. final float y) {
  1046. return addTextWatermark(src, content, textSize, color, x, y, false);
  1047. }
  1048. /**
  1049. * Return the bitmap with text watermarking.
  1050. *
  1051. * @param src The source of bitmap.
  1052. * @param content The content of text.
  1053. * @param textSize The size of text.
  1054. * @param color The color of text.
  1055. * @param x The x coordinate of the first pixel.
  1056. * @param y The y coordinate of the first pixel.
  1057. * @param recycle True to recycle the source of bitmap, false otherwise.
  1058. * @return the bitmap with text watermarking
  1059. */
  1060. public static Bitmap addTextWatermark(final Bitmap src,
  1061. final String content,
  1062. final float textSize,
  1063. @ColorInt final int color,
  1064. final float x,
  1065. final float y,
  1066. final boolean recycle) {
  1067. if (isEmptyBitmap(src) || content == null) return null;
  1068. Bitmap ret = src.copy(src.getConfig(), true);
  1069. Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  1070. Canvas canvas = new Canvas(ret);
  1071. paint.setColor(color);
  1072. paint.setTextSize(textSize);
  1073. Rect bounds = new Rect();
  1074. paint.getTextBounds(content, 0, content.length(), bounds);
  1075. canvas.drawText(content, x, y + textSize, paint);
  1076. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  1077. return ret;
  1078. }
  1079. /**
  1080. * Return the bitmap with image watermarking.
  1081. *
  1082. * @param src The source of bitmap.
  1083. * @param watermark The image watermarking.
  1084. * @param x The x coordinate of the first pixel.
  1085. * @param y The y coordinate of the first pixel.
  1086. * @param alpha The alpha of watermark.
  1087. * @return the bitmap with image watermarking
  1088. */
  1089. public static Bitmap addImageWatermark(final Bitmap src,
  1090. final Bitmap watermark,
  1091. final int x, final int y,
  1092. final int alpha) {
  1093. return addImageWatermark(src, watermark, x, y, alpha, false);
  1094. }
  1095. /**
  1096. * Return the bitmap with image watermarking.
  1097. *
  1098. * @param src The source of bitmap.
  1099. * @param watermark The image watermarking.
  1100. * @param x The x coordinate of the first pixel.
  1101. * @param y The y coordinate of the first pixel.
  1102. * @param alpha The alpha of watermark.
  1103. * @param recycle True to recycle the source of bitmap, false otherwise.
  1104. * @return the bitmap with image watermarking
  1105. */
  1106. public static Bitmap addImageWatermark(final Bitmap src,
  1107. final Bitmap watermark,
  1108. final int x,
  1109. final int y,
  1110. final int alpha,
  1111. final boolean recycle) {
  1112. if (isEmptyBitmap(src)) return null;
  1113. Bitmap ret = src.copy(src.getConfig(), true);
  1114. if (!isEmptyBitmap(watermark)) {
  1115. Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  1116. Canvas canvas = new Canvas(ret);
  1117. paint.setAlpha(alpha);
  1118. canvas.drawBitmap(watermark, x, y, paint);
  1119. }
  1120. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  1121. return ret;
  1122. }
  1123. /**
  1124. * Return the alpha bitmap.
  1125. *
  1126. * @param src The source of bitmap.
  1127. * @return the alpha bitmap
  1128. */
  1129. public static Bitmap toAlpha(final Bitmap src) {
  1130. return toAlpha(src, false);
  1131. }
  1132. /**
  1133. * Return the alpha bitmap.
  1134. *
  1135. * @param src The source of bitmap.
  1136. * @param recycle True to recycle the source of bitmap, false otherwise.
  1137. * @return the alpha bitmap
  1138. */
  1139. public static Bitmap toAlpha(final Bitmap src, final Boolean recycle) {
  1140. if (isEmptyBitmap(src)) return null;
  1141. Bitmap ret = src.extractAlpha();
  1142. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  1143. return ret;
  1144. }
  1145. /**
  1146. * Return the gray bitmap.
  1147. *
  1148. * @param src The source of bitmap.
  1149. * @return the gray bitmap
  1150. */
  1151. public static Bitmap toGray(final Bitmap src) {
  1152. return toGray(src, false);
  1153. }
  1154. /**
  1155. * Return the gray bitmap.
  1156. *
  1157. * @param src The source of bitmap.
  1158. * @param recycle True to recycle the source of bitmap, false otherwise.
  1159. * @return the gray bitmap
  1160. */
  1161. public static Bitmap toGray(final Bitmap src, final boolean recycle) {
  1162. if (isEmptyBitmap(src)) return null;
  1163. Bitmap ret = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
  1164. Canvas canvas = new Canvas(ret);
  1165. Paint paint = new Paint();
  1166. ColorMatrix colorMatrix = new ColorMatrix();
  1167. colorMatrix.setSaturation(0);
  1168. ColorMatrixColorFilter colorMatrixColorFilter = new ColorMatrixColorFilter(colorMatrix);
  1169. paint.setColorFilter(colorMatrixColorFilter);
  1170. canvas.drawBitmap(src, 0, 0, paint);
  1171. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  1172. return ret;
  1173. }
  1174. /**
  1175. * Return the blur bitmap fast.
  1176. * <p>zoom out, blur, zoom in</p>
  1177. *
  1178. * @param src The source of bitmap.
  1179. * @param scale The scale(0...1).
  1180. * @param radius The radius(0...25).
  1181. * @return the blur bitmap
  1182. */
  1183. public static Bitmap fastBlur(final Bitmap src,
  1184. @FloatRange(
  1185. from = 0, to = 1, fromInclusive = false
  1186. ) final float scale,
  1187. @FloatRange(
  1188. from = 0, to = 25, fromInclusive = false
  1189. ) final float radius) {
  1190. return fastBlur(src, scale, radius, false, false);
  1191. }
  1192. /**
  1193. * Return the blur bitmap fast.
  1194. * <p>zoom out, blur, zoom in</p>
  1195. *
  1196. * @param src The source of bitmap.
  1197. * @param scale The scale(0...1).
  1198. * @param radius The radius(0...25).
  1199. * @return the blur bitmap
  1200. */
  1201. public static Bitmap fastBlur(final Bitmap src,
  1202. @FloatRange(
  1203. from = 0, to = 1, fromInclusive = false
  1204. ) final float scale,
  1205. @FloatRange(
  1206. from = 0, to = 25, fromInclusive = false
  1207. ) final float radius,
  1208. final boolean recycle) {
  1209. return fastBlur(src, scale, radius, recycle, false);
  1210. }
  1211. /**
  1212. * Return the blur bitmap fast.
  1213. * <p>zoom out, blur, zoom in</p>
  1214. *
  1215. * @param src The source of bitmap.
  1216. * @param scale The scale(0...1).
  1217. * @param radius The radius(0...25).
  1218. * @param recycle True to recycle the source of bitmap, false otherwise.
  1219. * @param isReturnScale True to return the scale blur bitmap, false otherwise.
  1220. * @return the blur bitmap
  1221. */
  1222. public static Bitmap fastBlur(final Bitmap src,
  1223. @FloatRange(
  1224. from = 0, to = 1, fromInclusive = false
  1225. ) final float scale,
  1226. @FloatRange(
  1227. from = 0, to = 25, fromInclusive = false
  1228. ) final float radius,
  1229. final boolean recycle,
  1230. final boolean isReturnScale) {
  1231. if (isEmptyBitmap(src)) return null;
  1232. int width = src.getWidth();
  1233. int height = src.getHeight();
  1234. Matrix matrix = new Matrix();
  1235. matrix.setScale(scale, scale);
  1236. Bitmap scaleBitmap =
  1237. Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
  1238. Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG);
  1239. Canvas canvas = new Canvas();
  1240. PorterDuffColorFilter filter = new PorterDuffColorFilter(
  1241. Color.TRANSPARENT, PorterDuff.Mode.SRC_ATOP);
  1242. paint.setColorFilter(filter);
  1243. canvas.scale(scale, scale);
  1244. canvas.drawBitmap(scaleBitmap, 0, 0, paint);
  1245. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
  1246. scaleBitmap = renderScriptBlur(scaleBitmap, radius, recycle);
  1247. } else {
  1248. scaleBitmap = stackBlur(scaleBitmap, (int) radius, recycle);
  1249. }
  1250. if (scale == 1 || isReturnScale) {
  1251. if (recycle && !src.isRecycled() && scaleBitmap != src) src.recycle();
  1252. return scaleBitmap;
  1253. }
  1254. Bitmap ret = Bitmap.createScaledBitmap(scaleBitmap, width, height, true);
  1255. if (!scaleBitmap.isRecycled()) scaleBitmap.recycle();
  1256. if (recycle && !src.isRecycled() && ret != src) src.recycle();
  1257. return ret;
  1258. }
  1259. /**
  1260. * Return the blur bitmap using render script.
  1261. *
  1262. * @param src The source of bitmap.
  1263. * @param radius The radius(0...25).
  1264. * @return the blur bitmap
  1265. */
  1266. @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
  1267. public static Bitmap renderScriptBlur(final Bitmap src,
  1268. @FloatRange(
  1269. from = 0, to = 25, fromInclusive = false
  1270. ) final float radius) {
  1271. return renderScriptBlur(src, radius, false);
  1272. }
  1273. /**
  1274. * Return the blur bitmap using render script.
  1275. *
  1276. * @param src The source of bitmap.
  1277. * @param radius The radius(0...25).
  1278. * @param recycle True to recycle the source of bitmap, false otherwise.
  1279. * @return the blur bitmap
  1280. */
  1281. @RequiresApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
  1282. public static Bitmap renderScriptBlur(final Bitmap src,
  1283. @FloatRange(
  1284. from = 0, to = 25, fromInclusive = false
  1285. ) final float radius,
  1286. final boolean recycle) {
  1287. RenderScript rs = null;
  1288. Bitmap ret = recycle ? src : src.copy(src.getConfig(), true);
  1289. try {
  1290. rs = RenderScript.create(Utils.getApp());
  1291. rs.setMessageHandler(new RenderScript.RSMessageHandler());
  1292. Allocation input = Allocation.createFromBitmap(rs,
  1293. ret,
  1294. Allocation.MipmapControl.MIPMAP_NONE,
  1295. Allocation.USAGE_SCRIPT);
  1296. Allocation output = Allocation.createTyped(rs, input.getType());
  1297. ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
  1298. blurScript.setInput(input);
  1299. blurScript.setRadius(radius);
  1300. blurScript.forEach(output);
  1301. output.copyTo(ret);
  1302. } finally {
  1303. if (rs != null) {
  1304. rs.destroy();
  1305. }
  1306. }
  1307. return ret;
  1308. }
  1309. /**
  1310. * Return the blur bitmap using stack.
  1311. *
  1312. * @param src The source of bitmap.
  1313. * @param radius The radius(0...25).
  1314. * @return the blur bitmap
  1315. */
  1316. public static Bitmap stackBlur(final Bitmap src, final int radius) {
  1317. return stackBlur(src, radius, false);
  1318. }
  1319. /**
  1320. * Return the blur bitmap using stack.
  1321. *
  1322. * @param src The source of bitmap.
  1323. * @param radius The radius(0...25).
  1324. * @param recycle True to recycle the source of bitmap, false otherwise.
  1325. * @return the blur bitmap
  1326. */
  1327. public static Bitmap stackBlur(final Bitmap src, int radius, final boolean recycle) {
  1328. Bitmap ret = recycle ? src : src.copy(src.getConfig(), true);
  1329. if (radius < 1) {
  1330. radius = 1;
  1331. }
  1332. int w = ret.getWidth();
  1333. int h = ret.getHeight();
  1334. int[] pix = new int[w * h];
  1335. ret.getPixels(pix, 0, w, 0, 0, w, h);
  1336. int wm = w - 1;
  1337. int hm = h - 1;
  1338. int wh = w * h;
  1339. int div = radius + radius + 1;
  1340. int r[] = new int[wh];
  1341. int g[] = new int[wh];
  1342. int b[] = new int[wh];
  1343. int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
  1344. int vmin[] = new int[Math.max(w, h)];
  1345. int divsum = (div + 1) >> 1;
  1346. divsum *= divsum;
  1347. int dv[] = new int[256 * divsum];
  1348. for (i = 0; i < 256 * divsum; i++) {
  1349. dv[i] = (i / divsum);
  1350. }
  1351. yw = yi = 0;
  1352. int[][] stack = new int[div][3];
  1353. int stackpointer;
  1354. int stackstart;
  1355. int[] sir;
  1356. int rbs;
  1357. int r1 = radius + 1;
  1358. int routsum, goutsum, boutsum;
  1359. int rinsum, ginsum, binsum;
  1360. for (y = 0; y < h; y++) {
  1361. rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
  1362. for (i = -radius; i <= radius; i++) {
  1363. p = pix[yi + Math.min(wm, Math.max(i, 0))];
  1364. sir = stack[i + radius];
  1365. sir[0] = (p & 0xff0000) >> 16;
  1366. sir[1] = (p & 0x00ff00) >> 8;
  1367. sir[2] = (p & 0x0000ff);
  1368. rbs = r1 - Math.abs(i);
  1369. rsum += sir[0] * rbs;
  1370. gsum += sir[1] * rbs;
  1371. bsum += sir[2] * rbs;
  1372. if (i > 0) {
  1373. rinsum += sir[0];
  1374. ginsum += sir[1];
  1375. binsum += sir[2];
  1376. } else {
  1377. routsum += sir[0];
  1378. goutsum += sir[1];
  1379. boutsum += sir[2];
  1380. }
  1381. }
  1382. stackpointer = radius;
  1383. for (x = 0; x < w; x++) {
  1384. r[yi] = dv[rsum];
  1385. g[yi] = dv[gsum];
  1386. b[yi] = dv[bsum];
  1387. rsum -= routsum;
  1388. gsum -= goutsum;
  1389. bsum -= boutsum;
  1390. stackstart = stackpointer - radius + div;
  1391. sir = stack[stackstart % div];
  1392. routsum -= sir[0];
  1393. goutsum -= sir[1];
  1394. boutsum -= sir[2];
  1395. if (y == 0) {
  1396. vmin[x] = Math.min(x + radius + 1, wm);
  1397. }
  1398. p = pix[yw + vmin[x]];
  1399. sir[0] = (p & 0xff0000) >> 16;
  1400. sir[1] = (p & 0x00ff00) >> 8;
  1401. sir[2] = (p & 0x0000ff);
  1402. rinsum += sir[0];
  1403. ginsum += sir[1];
  1404. binsum += sir[2];
  1405. rsum += rinsum;
  1406. gsum += ginsum;
  1407. bsum += binsum;
  1408. stackpointer = (stackpointer + 1) % div;
  1409. sir = stack[(stackpointer) % div];
  1410. routsum += sir[0];
  1411. goutsum += sir[1];
  1412. boutsum += sir[2];
  1413. rinsum -= sir[0];
  1414. ginsum -= sir[1];
  1415. binsum -= sir[2];
  1416. yi++;
  1417. }
  1418. yw += w;
  1419. }
  1420. for (x = 0; x < w; x++) {
  1421. rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
  1422. yp = -radius * w;
  1423. for (i = -radius; i <= radius; i++) {
  1424. yi = Math.max(0, yp) + x;
  1425. sir = stack[i + radius];
  1426. sir[0] = r[yi];
  1427. sir[1] = g[yi];
  1428. sir[2] = b[yi];
  1429. rbs = r1 - Math.abs(i);
  1430. rsum += r[yi] * rbs;
  1431. gsum += g[yi] * rbs;
  1432. bsum += b[yi] * rbs;
  1433. if (i > 0) {
  1434. rinsum += sir[0];
  1435. ginsum += sir[1];
  1436. binsum += sir[2];
  1437. } else {
  1438. routsum += sir[0];
  1439. goutsum += sir[1];
  1440. boutsum += sir[2];
  1441. }
  1442. if (i < hm) {
  1443. yp += w;
  1444. }
  1445. }
  1446. yi = x;
  1447. stackpointer = radius;
  1448. for (y = 0; y < h; y++) {
  1449. // Preserve alpha channel: ( 0xff000000 & pix[yi] )
  1450. pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];
  1451. rsum -= routsum;
  1452. gsum -= goutsum;
  1453. bsum -= boutsum;
  1454. stackstart = stackpointer - radius + div;
  1455. sir = stack[stackstart % div];
  1456. routsum -= sir[0];
  1457. goutsum -= sir[1];
  1458. boutsum -= sir[2];
  1459. if (x == 0) {
  1460. vmin[y] = Math.min(y + r1, hm) * w;
  1461. }
  1462. p = x + vmin[y];
  1463. sir[0] = r[p];
  1464. sir[1] = g[p];
  1465. sir[2] = b[p];
  1466. rinsum += sir[0];
  1467. ginsum += sir[1];
  1468. binsum += sir[2];
  1469. rsum += rinsum;
  1470. gsum += ginsum;
  1471. bsum += binsum;
  1472. stackpointer = (stackpointer + 1) % div;
  1473. sir = stack[stackpointer];
  1474. routsum += sir[0];
  1475. goutsum += sir[1];
  1476. boutsum += sir[2];
  1477. rinsum -= sir[0];
  1478. ginsum -= sir[1];
  1479. binsum -= sir[2];
  1480. yi += w;
  1481. }
  1482. }
  1483. ret.setPixels(pix, 0, w, 0, 0, w, h);
  1484. return ret;
  1485. }
  1486. /**
  1487. * Save the bitmap.
  1488. *
  1489. * @param src The source of bitmap.
  1490. * @param filePath The path of file.
  1491. * @param format The format of the image.
  1492. * @return {@code true}: success<br>{@code false}: fail
  1493. */
  1494. public static boolean save(final Bitmap src,
  1495. final String filePath,
  1496. final CompressFormat format) {
  1497. return save(src, filePath, format, 100, false);
  1498. }
  1499. /**
  1500. * Save the bitmap.
  1501. *
  1502. * @param src The source of bitmap.
  1503. * @param file The file.
  1504. * @param format The format of the image.
  1505. * @return {@code true}: success<br>{@code false}: fail
  1506. */
  1507. public static boolean save(final Bitmap src, final File file, final CompressFormat format) {
  1508. return save(src, file, format, 100, false);
  1509. }
  1510. /**
  1511. * Save the bitmap.
  1512. *
  1513. * @param src The source of bitmap.
  1514. * @param filePath The path of file.
  1515. * @param format The format of the image.
  1516. * @param recycle True to recycle the source of bitmap, false otherwise.
  1517. * @return {@code true}: success<br>{@code false}: fail
  1518. */
  1519. public static boolean save(final Bitmap src,
  1520. final String filePath,
  1521. final CompressFormat format,
  1522. final boolean recycle) {
  1523. return save(src, filePath, format, 100, recycle);
  1524. }
  1525. /**
  1526. * Save the bitmap.
  1527. *
  1528. * @param src The source of bitmap.
  1529. * @param file The file.
  1530. * @param format The format of the image.
  1531. * @param recycle True to recycle the source of bitmap, false otherwise.
  1532. * @return {@code true}: success<br>{@code false}: fail
  1533. */
  1534. public static boolean save(final Bitmap src,
  1535. final File file,
  1536. final CompressFormat format,
  1537. final boolean recycle) {
  1538. return save(src, file, format, 100, recycle);
  1539. }
  1540. /**
  1541. * Save the bitmap.
  1542. *
  1543. * @param src The source of bitmap.
  1544. * @param filePath The path of file.
  1545. * @param format The format of the image.
  1546. * @param quality Hint to the compressor, 0-100. 0 meaning compress for
  1547. * small size, 100 meaning compress for max quality. Some
  1548. * formats, like PNG which is lossless, will ignore the
  1549. * quality setting
  1550. * @return {@code true}: success<br>{@code false}: fail
  1551. */
  1552. public static boolean save(final Bitmap src,
  1553. final String filePath,
  1554. final CompressFormat format,
  1555. final int quality) {
  1556. return save(src, UtilsBridge.getFileByPath(filePath), format, quality, false);
  1557. }
  1558. /**
  1559. * Save the bitmap.
  1560. *
  1561. * @param src The source of bitmap.
  1562. * @param file The file.
  1563. * @param format The format of the image.
  1564. * @return {@code true}: success<br>{@code false}: fail
  1565. */
  1566. public static boolean save(final Bitmap src,
  1567. final File file,
  1568. final CompressFormat format,
  1569. final int quality) {
  1570. return save(src, file, format, quality, false);
  1571. }
  1572. /**
  1573. * Save the bitmap.
  1574. *
  1575. * @param src The source of bitmap.
  1576. * @param filePath The path of file.
  1577. * @param format The format of the image.
  1578. * @param quality Hint to the compressor, 0-100. 0 meaning compress for
  1579. * small size, 100 meaning compress for max quality. Some
  1580. * formats, like PNG which is lossless, will ignore the
  1581. * quality setting
  1582. * @param recycle True to recycle the source of bitmap, false otherwise.
  1583. * @return {@code true}: success<br>{@code false}: fail
  1584. */
  1585. public static boolean save(final Bitmap src,
  1586. final String filePath,
  1587. final CompressFormat format,
  1588. final int quality,
  1589. final boolean recycle) {
  1590. return save(src, UtilsBridge.getFileByPath(filePath), format, quality, recycle);
  1591. }
  1592. /**
  1593. * Save the bitmap.
  1594. *
  1595. * @param src The source of bitmap.
  1596. * @param file The file.
  1597. * @param format The format of the image.
  1598. * @param quality Hint to the compressor, 0-100. 0 meaning compress for
  1599. * small size, 100 meaning compress for max quality. Some
  1600. * formats, like PNG which is lossless, will ignore the
  1601. * quality setting
  1602. * @param recycle True to recycle the source of bitmap, false otherwise.
  1603. * @return {@code true}: success<br>{@code false}: fail
  1604. */
  1605. public static boolean save(final Bitmap src,
  1606. final File file,
  1607. final CompressFormat format,
  1608. final int quality,
  1609. final boolean recycle) {
  1610. if (isEmptyBitmap(src)) {
  1611. Log.e("ImageUtils", "bitmap is empty.");
  1612. return false;
  1613. }
  1614. if (src.isRecycled()) {
  1615. Log.e("ImageUtils", "bitmap is recycled.");
  1616. return false;
  1617. }
  1618. if (!UtilsBridge.createFileByDeleteOldFile(file)) {
  1619. Log.e("ImageUtils", "create or delete file <" + file + "> failed.");
  1620. return false;
  1621. }
  1622. OutputStream os = null;
  1623. boolean ret = false;
  1624. try {
  1625. os = new BufferedOutputStream(new FileOutputStream(file));
  1626. ret = src.compress(format, quality, os);
  1627. if (recycle && !src.isRecycled()) src.recycle();
  1628. } catch (IOException e) {
  1629. e.printStackTrace();
  1630. } finally {
  1631. try {
  1632. if (os != null) {
  1633. os.close();
  1634. }
  1635. } catch (IOException e) {
  1636. e.printStackTrace();
  1637. }
  1638. }
  1639. return ret;
  1640. }
  1641. /**
  1642. * @param src The source of bitmap.
  1643. * @param format The format of the image.
  1644. * @return the file if save success, otherwise return null.
  1645. */
  1646. @Nullable
  1647. public static File save2Album(final Bitmap src,
  1648. final CompressFormat format) {
  1649. return save2Album(src, "", format, 100, false);
  1650. }
  1651. /**
  1652. * @param src The source of bitmap.
  1653. * @param format The format of the image.
  1654. * @param recycle True to recycle the source of bitmap, false otherwise.
  1655. * @return the file if save success, otherwise return null.
  1656. */
  1657. @Nullable
  1658. public static File save2Album(final Bitmap src,
  1659. final CompressFormat format,
  1660. final boolean recycle) {
  1661. return save2Album(src, "", format, 100, recycle);
  1662. }
  1663. /**
  1664. * @param src The source of bitmap.
  1665. * @param format The format of the image.
  1666. * @param quality Hint to the compressor, 0-100. 0 meaning compress for
  1667. * small size, 100 meaning compress for max quality. Some
  1668. * formats, like PNG which is lossless, will ignore the
  1669. * quality setting
  1670. * @return the file if save success, otherwise return null.
  1671. */
  1672. @Nullable
  1673. public static File save2Album(final Bitmap src,
  1674. final CompressFormat format,
  1675. final int quality) {
  1676. return save2Album(src, "", format, quality, false);
  1677. }
  1678. /**
  1679. * @param src The source of bitmap.
  1680. * @param format The format of the image.
  1681. * @param quality Hint to the compressor, 0-100. 0 meaning compress for
  1682. * small size, 100 meaning compress for max quality. Some
  1683. * formats, like PNG which is lossless, will ignore the
  1684. * quality setting
  1685. * @param recycle True to recycle the source of bitmap, false otherwise.
  1686. * @return the file if save success, otherwise return null.
  1687. */
  1688. @Nullable
  1689. public static File save2Album(final Bitmap src,
  1690. final CompressFormat format,
  1691. final int quality,
  1692. final boolean recycle) {
  1693. return save2Album(src, "", format, quality, recycle);
  1694. }
  1695. /**
  1696. * @param src The source of bitmap.
  1697. * @param dirName The name of directory.
  1698. * @param format The format of the image.
  1699. * @return the file if save success, otherwise return null.
  1700. */
  1701. @Nullable
  1702. public static File save2Album(final Bitmap src,
  1703. final String dirName,
  1704. final CompressFormat format) {
  1705. return save2Album(src, dirName, format, 100, false);
  1706. }
  1707. /**
  1708. * @param src The source of bitmap.
  1709. * @param dirName The name of directory.
  1710. * @param format The format of the image.
  1711. * @param recycle True to recycle the source of bitmap, false otherwise.
  1712. * @return the file if save success, otherwise return null.
  1713. */
  1714. @Nullable
  1715. public static File save2Album(final Bitmap src,
  1716. final String dirName,
  1717. final CompressFormat format,
  1718. final boolean recycle) {
  1719. return save2Album(src, dirName, format, 100, recycle);
  1720. }
  1721. /**
  1722. * @param src The source of bitmap.
  1723. * @param dirName The name of directory.
  1724. * @param format The format of the image.
  1725. * @param quality Hint to the compressor, 0-100. 0 meaning compress for
  1726. * small size, 100 meaning compress for max quality. Some
  1727. * formats, like PNG which is lossless, will ignore the
  1728. * quality setting
  1729. * @return the file if save success, otherwise return null.
  1730. */
  1731. @Nullable
  1732. public static File save2Album(final Bitmap src,
  1733. final String dirName,
  1734. final CompressFormat format,
  1735. final int quality) {
  1736. return save2Album(src, dirName, format, quality, false);
  1737. }
  1738. /**
  1739. * @param src The source of bitmap.
  1740. * @param dirName The name of directory.
  1741. * @param format The format of the image.
  1742. * @param quality Hint to the compressor, 0-100. 0 meaning compress for
  1743. * small size, 100 meaning compress for max quality. Some
  1744. * formats, like PNG which is lossless, will ignore the
  1745. * quality setting
  1746. * @param recycle True to recycle the source of bitmap, false otherwise.
  1747. * @return the file if save success, otherwise return null.
  1748. */
  1749. @Nullable
  1750. public static File save2Album(final Bitmap src,
  1751. final String dirName,
  1752. final CompressFormat format,
  1753. final int quality,
  1754. final boolean recycle) {
  1755. String safeDirName = TextUtils.isEmpty(dirName) ? Utils.getApp().getPackageName() : dirName;
  1756. String suffix = CompressFormat.JPEG.equals(format) ? "JPG" : format.name();
  1757. String fileName = System.currentTimeMillis() + "_" + quality + "." + suffix;
  1758. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
  1759. if (!UtilsBridge.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
  1760. Log.e("ImageUtils", "save to album need storage permission");
  1761. return null;
  1762. }
  1763. File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
  1764. File destFile = new File(picDir, safeDirName + "/" + fileName);
  1765. if (!save(src, destFile, format, quality, recycle)) {
  1766. return null;
  1767. }
  1768. UtilsBridge.notifySystemToScan(destFile);
  1769. return destFile;
  1770. } else {
  1771. ContentValues contentValues = new ContentValues();
  1772. contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
  1773. contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/*");
  1774. Uri contentUri;
  1775. if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
  1776. contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
  1777. } else {
  1778. contentUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
  1779. }
  1780. contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/" + safeDirName);
  1781. contentValues.put(MediaStore.MediaColumns.IS_PENDING, 1);
  1782. Uri uri = Utils.getApp().getContentResolver().insert(contentUri, contentValues);
  1783. if (uri == null) {
  1784. return null;
  1785. }
  1786. OutputStream os = null;
  1787. try {
  1788. os = Utils.getApp().getContentResolver().openOutputStream(uri);
  1789. src.compress(format, quality, os);
  1790. contentValues.clear();
  1791. contentValues.put(MediaStore.MediaColumns.IS_PENDING, 0);
  1792. Utils.getApp().getContentResolver().update(uri, contentValues, null, null);
  1793. return UtilsBridge.uri2File(uri);
  1794. } catch (Exception e) {
  1795. Utils.getApp().getContentResolver().delete(uri, null, null);
  1796. e.printStackTrace();
  1797. return null;
  1798. } finally {
  1799. try {
  1800. if (os != null) {
  1801. os.close();
  1802. }
  1803. } catch (IOException e) {
  1804. e.printStackTrace();
  1805. }
  1806. }
  1807. }
  1808. }
  1809. /**
  1810. * Return whether it is a image according to the file name.
  1811. *
  1812. * @param file The file.
  1813. * @return {@code true}: yes<br>{@code false}: no
  1814. */
  1815. public static boolean isImage(final File file) {
  1816. if (file == null || !file.exists()) {
  1817. return false;
  1818. }
  1819. return isImage(file.getPath());
  1820. }
  1821. /**
  1822. * Return whether it is a image according to the file name.
  1823. *
  1824. * @param filePath The path of file.
  1825. * @return {@code true}: yes<br>{@code false}: no
  1826. */
  1827. public static boolean isImage(final String filePath) {
  1828. try {
  1829. BitmapFactory.Options options = new BitmapFactory.Options();
  1830. options.inJustDecodeBounds = true;
  1831. BitmapFactory.decodeFile(filePath, options);
  1832. return options.outWidth > 0 && options.outHeight > 0;
  1833. } catch (Exception e) {
  1834. return false;
  1835. }
  1836. }
  1837. /**
  1838. * Return the type of image.
  1839. *
  1840. * @param filePath The path of file.
  1841. * @return the type of image
  1842. */
  1843. public static ImageType getImageType(final String filePath) {
  1844. return getImageType(UtilsBridge.getFileByPath(filePath));
  1845. }
  1846. /**
  1847. * Return the type of image.
  1848. *
  1849. * @param file The file.
  1850. * @return the type of image
  1851. */
  1852. public static ImageType getImageType(final File file) {
  1853. if (file == null) return null;
  1854. InputStream is = null;
  1855. try {
  1856. is = new FileInputStream(file);
  1857. ImageType type = getImageType(is);
  1858. if (type != null) {
  1859. return type;
  1860. }
  1861. } catch (IOException e) {
  1862. e.printStackTrace();
  1863. } finally {
  1864. try {
  1865. if (is != null) {
  1866. is.close();
  1867. }
  1868. } catch (IOException e) {
  1869. e.printStackTrace();
  1870. }
  1871. }
  1872. return null;
  1873. }
  1874. private static ImageType getImageType(final InputStream is) {
  1875. if (is == null) return null;
  1876. try {
  1877. byte[] bytes = new byte[12];
  1878. return is.read(bytes) != -1 ? getImageType(bytes) : null;
  1879. } catch (IOException e) {
  1880. e.printStackTrace();
  1881. return null;
  1882. }
  1883. }
  1884. private static ImageType getImageType(final byte[] bytes) {
  1885. String type = UtilsBridge.bytes2HexString(bytes).toUpperCase();
  1886. if (type.contains("FFD8FF")) {
  1887. return ImageType.TYPE_JPG;
  1888. } else if (type.contains("89504E47")) {
  1889. return ImageType.TYPE_PNG;
  1890. } else if (type.contains("47494638")) {
  1891. return ImageType.TYPE_GIF;
  1892. } else if (type.contains("49492A00") || type.contains("4D4D002A")) {
  1893. return ImageType.TYPE_TIFF;
  1894. } else if (type.contains("424D")) {
  1895. return ImageType.TYPE_BMP;
  1896. } else if (type.startsWith("52494646") && type.endsWith("57454250")) {//524946461c57000057454250-12个字节
  1897. return ImageType.TYPE_WEBP;
  1898. } else if (type.contains("00000100") || type.contains("00000200")) {
  1899. return ImageType.TYPE_ICO;
  1900. } else {
  1901. return ImageType.TYPE_UNKNOWN;
  1902. }
  1903. }
  1904. private static boolean isJPEG(final byte[] b) {
  1905. return b.length >= 2
  1906. && (b[0] == (byte) 0xFF) && (b[1] == (byte) 0xD8);
  1907. }
  1908. private static boolean isGIF(final byte[] b) {
  1909. return b.length >= 6
  1910. && b[0] == 'G' && b[1] == 'I'
  1911. && b[2] == 'F' && b[3] == '8'
  1912. && (b[4] == '7' || b[4] == '9') && b[5] == 'a';
  1913. }
  1914. private static boolean isPNG(final byte[] b) {
  1915. return b.length >= 8
  1916. && (b[0] == (byte) 137 && b[1] == (byte) 80
  1917. && b[2] == (byte) 78 && b[3] == (byte) 71
  1918. && b[4] == (byte) 13 && b[5] == (byte) 10
  1919. && b[6] == (byte) 26 && b[7] == (byte) 10);
  1920. }
  1921. private static boolean isBMP(final byte[] b) {
  1922. return b.length >= 2
  1923. && (b[0] == 0x42) && (b[1] == 0x4d);
  1924. }
  1925. private static boolean isEmptyBitmap(final Bitmap src) {
  1926. return src == null || src.getWidth() == 0 || src.getHeight() == 0;
  1927. }
  1928. ///////////////////////////////////////////////////////////////////////////
  1929. // about compress
  1930. ///////////////////////////////////////////////////////////////////////////
  1931. /**
  1932. * Return the compressed bitmap using scale.
  1933. *
  1934. * @param src The source of bitmap.
  1935. * @param newWidth The new width.
  1936. * @param newHeight The new height.
  1937. * @return the compressed bitmap
  1938. */
  1939. public static Bitmap compressByScale(final Bitmap src,
  1940. final int newWidth,
  1941. final int newHeight) {
  1942. return scale(src, newWidth, newHeight, false);
  1943. }
  1944. /**
  1945. * Return the compressed bitmap using scale.
  1946. *
  1947. * @param src The source of bitmap.
  1948. * @param newWidth The new width.
  1949. * @param newHeight The new height.
  1950. * @param recycle True to recycle the source of bitmap, false otherwise.
  1951. * @return the compressed bitmap
  1952. */
  1953. public static Bitmap compressByScale(final Bitmap src,
  1954. final int newWidth,
  1955. final int newHeight,
  1956. final boolean recycle) {
  1957. return scale(src, newWidth, newHeight, recycle);
  1958. }
  1959. /**
  1960. * Return the compressed bitmap using scale.
  1961. *
  1962. * @param src The source of bitmap.
  1963. * @param scaleWidth The scale of width.
  1964. * @param scaleHeight The scale of height.
  1965. * @return the compressed bitmap
  1966. */
  1967. public static Bitmap compressByScale(final Bitmap src,
  1968. final float scaleWidth,
  1969. final float scaleHeight) {
  1970. return scale(src, scaleWidth, scaleHeight, false);
  1971. }
  1972. /**
  1973. * Return the compressed bitmap using scale.
  1974. *
  1975. * @param src The source of bitmap.
  1976. * @param scaleWidth The scale of width.
  1977. * @param scaleHeight The scale of height.
  1978. * @param recycle True to recycle the source of bitmap, false otherwise.
  1979. * @return he compressed bitmap
  1980. */
  1981. public static Bitmap compressByScale(final Bitmap src,
  1982. final float scaleWidth,
  1983. final float scaleHeight,
  1984. final boolean recycle) {
  1985. return scale(src, scaleWidth, scaleHeight, recycle);
  1986. }
  1987. /**
  1988. * Return the compressed data using quality.
  1989. *
  1990. * @param src The source of bitmap.
  1991. * @param quality The quality.
  1992. * @return the compressed data using quality
  1993. */
  1994. public static byte[] compressByQuality(final Bitmap src,
  1995. @IntRange(from = 0, to = 100) final int quality) {
  1996. return compressByQuality(src, quality, false);
  1997. }
  1998. /**
  1999. * Return the compressed data using quality.
  2000. *
  2001. * @param src The source of bitmap.
  2002. * @param quality The quality.
  2003. * @param recycle True to recycle the source of bitmap, false otherwise.
  2004. * @return the compressed data using quality
  2005. */
  2006. public static byte[] compressByQuality(final Bitmap src,
  2007. @IntRange(from = 0, to = 100) final int quality,
  2008. final boolean recycle) {
  2009. if (isEmptyBitmap(src)) return null;
  2010. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  2011. src.compress(Bitmap.CompressFormat.JPEG, quality, baos);
  2012. byte[] bytes = baos.toByteArray();
  2013. if (recycle && !src.isRecycled()) src.recycle();
  2014. return bytes;
  2015. }
  2016. /**
  2017. * Return the compressed data using quality.
  2018. *
  2019. * @param src The source of bitmap.
  2020. * @param maxByteSize The maximum size of byte.
  2021. * @return the compressed data using quality
  2022. */
  2023. public static byte[] compressByQuality(final Bitmap src, final long maxByteSize) {
  2024. return compressByQuality(src, maxByteSize, false);
  2025. }
  2026. /**
  2027. * Return the compressed data using quality.
  2028. *
  2029. * @param src The source of bitmap.
  2030. * @param maxByteSize The maximum size of byte.
  2031. * @param recycle True to recycle the source of bitmap, false otherwise.
  2032. * @return the compressed data using quality
  2033. */
  2034. public static byte[] compressByQuality(final Bitmap src,
  2035. final long maxByteSize,
  2036. final boolean recycle) {
  2037. if (isEmptyBitmap(src) || maxByteSize <= 0) return new byte[0];
  2038. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  2039. src.compress(CompressFormat.JPEG, 100, baos);
  2040. byte[] bytes;
  2041. if (baos.size() <= maxByteSize) {
  2042. bytes = baos.toByteArray();
  2043. } else {
  2044. baos.reset();
  2045. src.compress(CompressFormat.JPEG, 0, baos);
  2046. if (baos.size() >= maxByteSize) {
  2047. bytes = baos.toByteArray();
  2048. } else {
  2049. // find the best quality using binary search
  2050. int st = 0;
  2051. int end = 100;
  2052. int mid = 0;
  2053. while (st < end) {
  2054. mid = (st + end) / 2;
  2055. baos.reset();
  2056. src.compress(CompressFormat.JPEG, mid, baos);
  2057. int len = baos.size();
  2058. if (len == maxByteSize) {
  2059. break;
  2060. } else if (len > maxByteSize) {
  2061. end = mid - 1;
  2062. } else {
  2063. st = mid + 1;
  2064. }
  2065. }
  2066. if (end == mid - 1) {
  2067. baos.reset();
  2068. src.compress(CompressFormat.JPEG, st, baos);
  2069. }
  2070. bytes = baos.toByteArray();
  2071. }
  2072. }
  2073. if (recycle && !src.isRecycled()) src.recycle();
  2074. return bytes;
  2075. }
  2076. /**
  2077. * Return the compressed bitmap using sample size.
  2078. *
  2079. * @param src The source of bitmap.
  2080. * @param sampleSize The sample size.
  2081. * @return the compressed bitmap
  2082. */
  2083. public static Bitmap compressBySampleSize(final Bitmap src, final int sampleSize) {
  2084. return compressBySampleSize(src, sampleSize, false);
  2085. }
  2086. /**
  2087. * Return the compressed bitmap using sample size.
  2088. *
  2089. * @param src The source of bitmap.
  2090. * @param sampleSize The sample size.
  2091. * @param recycle True to recycle the source of bitmap, false otherwise.
  2092. * @return the compressed bitmap
  2093. */
  2094. public static Bitmap compressBySampleSize(final Bitmap src,
  2095. final int sampleSize,
  2096. final boolean recycle) {
  2097. if (isEmptyBitmap(src)) return null;
  2098. BitmapFactory.Options options = new BitmapFactory.Options();
  2099. options.inSampleSize = sampleSize;
  2100. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  2101. src.compress(Bitmap.CompressFormat.JPEG, 100, baos);
  2102. byte[] bytes = baos.toByteArray();
  2103. if (recycle && !src.isRecycled()) src.recycle();
  2104. return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
  2105. }
  2106. /**
  2107. * Return the compressed bitmap using sample size.
  2108. *
  2109. * @param src The source of bitmap.
  2110. * @param maxWidth The maximum width.
  2111. * @param maxHeight The maximum height.
  2112. * @return the compressed bitmap
  2113. */
  2114. public static Bitmap compressBySampleSize(final Bitmap src,
  2115. final int maxWidth,
  2116. final int maxHeight) {
  2117. return compressBySampleSize(src, maxWidth, maxHeight, false);
  2118. }
  2119. /**
  2120. * Return the compressed bitmap using sample size.
  2121. *
  2122. * @param src The source of bitmap.
  2123. * @param maxWidth The maximum width.
  2124. * @param maxHeight The maximum height.
  2125. * @param recycle True to recycle the source of bitmap, false otherwise.
  2126. * @return the compressed bitmap
  2127. */
  2128. public static Bitmap compressBySampleSize(final Bitmap src,
  2129. final int maxWidth,
  2130. final int maxHeight,
  2131. final boolean recycle) {
  2132. if (isEmptyBitmap(src)) return null;
  2133. BitmapFactory.Options options = new BitmapFactory.Options();
  2134. options.inJustDecodeBounds = true;
  2135. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  2136. src.compress(Bitmap.CompressFormat.JPEG, 100, baos);
  2137. byte[] bytes = baos.toByteArray();
  2138. BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
  2139. options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight);
  2140. options.inJustDecodeBounds = false;
  2141. if (recycle && !src.isRecycled()) src.recycle();
  2142. return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
  2143. }
  2144. /**
  2145. * Return the size of bitmap.
  2146. *
  2147. * @param filePath The path of file.
  2148. * @return the size of bitmap
  2149. */
  2150. public static int[] getSize(String filePath) {
  2151. return getSize(UtilsBridge.getFileByPath(filePath));
  2152. }
  2153. /**
  2154. * Return the size of bitmap.
  2155. *
  2156. * @param file The file.
  2157. * @return the size of bitmap
  2158. */
  2159. public static int[] getSize(File file) {
  2160. if (file == null) return new int[]{0, 0};
  2161. BitmapFactory.Options opts = new BitmapFactory.Options();
  2162. opts.inJustDecodeBounds = true;
  2163. BitmapFactory.decodeFile(file.getAbsolutePath(), opts);
  2164. return new int[]{opts.outWidth, opts.outHeight};
  2165. }
  2166. /**
  2167. * Return the sample size.
  2168. *
  2169. * @param options The options.
  2170. * @param maxWidth The maximum width.
  2171. * @param maxHeight The maximum height.
  2172. * @return the sample size
  2173. */
  2174. public static int calculateInSampleSize(final BitmapFactory.Options options,
  2175. final int maxWidth,
  2176. final int maxHeight) {
  2177. int height = options.outHeight;
  2178. int width = options.outWidth;
  2179. int inSampleSize = 1;
  2180. while (height > maxHeight || width > maxWidth) {
  2181. height >>= 1;
  2182. width >>= 1;
  2183. inSampleSize <<= 1;
  2184. }
  2185. return inSampleSize;
  2186. }
  2187. public enum ImageType {
  2188. TYPE_JPG("jpg"),
  2189. TYPE_PNG("png"),
  2190. TYPE_GIF("gif"),
  2191. TYPE_TIFF("tiff"),
  2192. TYPE_BMP("bmp"),
  2193. TYPE_WEBP("webp"),
  2194. TYPE_ICO("ico"),
  2195. TYPE_UNKNOWN("unknown");
  2196. String value;
  2197. ImageType(String value) {
  2198. this.value = value;
  2199. }
  2200. public String getValue() {
  2201. return value;
  2202. }
  2203. }
  2204. }