查看: 448|回复: 0

[Java代码] 缓存工具类

发表于 2017-8-7 08:00:02

安卓开发一般都需要进行数据缓存,常用操作老司机已为你封装完毕,经常有小伙伴问怎么判断缓存是否可用,那我告诉你,你可以用这份工具进行存储和查询,具体可以查看源码,现在为你开车,Demo传送门。

站点 缓存工具类 → AppACache

put : 保存String数据到缓存中
getAsString : 读取String数据
getAsJSONObject : 读取JSONObject数据
getAsJSONArray : 读取JSONArray数据
getAsBinary : 获取byte数据
getAsObject : 读取Serializable数据
getAsBitmap : 读取bitmap数据
getAsDrawable : 读取Drawable数据
file : 获取缓存文件
remove : 除某个key
clear : 清除所有数据

具体路线

public class AppACache {

  1. // 用法例子
  2. // ACache mCache = ACache.get(this); // 初始化,一般放在基类里
  3. // mCache.put("test_key1","test value");
  4. // mCache.put("test_key2", "test value", 10);// 保存10秒,如果超过10秒去获取这个key,将为null
  5. // mCache.put("test_key3", "test value", 2 ACache.TIME_DAY);// 保存两天,如果超过两天去获取这个key,将为null
  6. // String value = mCache.getAsString("test_key1");// 获取数据
  7. public static final int TIME_HOUR = 60 * 60;
  8. public static final int TIME_DAY = TIME_HOUR * 24;
  9. private static final int MAX_SIZE = 1000 * 1000 * 50; // 50 mb
  10. private static final int MAX_COUNT = Integer.MAX_VALUE; // 不限制存放数据的数量
  11. private static Map<String, AppACache> mInstanceMap = new HashMap<String, AppACache>();
  12. private ACacheManager mCache;
  13. public static AppACache get(Context ctx) {
  14. return get(ctx, "ACache");
  15. }
  16. public static AppACache get(Context ctx, String cacheName) {
  17. File f = new File(ctx.getCacheDir(), cacheName);
  18. return get(f, MAX_SIZE, MAX_COUNT);
  19. }
  20. public static AppACache get(File cacheDir) {
  21. return get(cacheDir, MAX_SIZE, MAX_COUNT);
  22. }
  23. public static AppACache get(Context ctx, long max_zise, int max_count) {
  24. File f = new File(ctx.getCacheDir(), "ACache");
  25. return get(f, max_zise, max_count);
  26. }
  27. public static AppACache get(File cacheDir, long max_zise, int max_count) {
  28. AppACache manager = mInstanceMap.get(cacheDir.getAbsoluteFile() + myPid());
  29. if (manager == null) {
  30. manager = new AppACache(cacheDir, max_zise, max_count);
  31. mInstanceMap.put(cacheDir.getAbsolutePath() + myPid(), manager);
  32. }
  33. return manager;
  34. }
  35. private static String myPid() {
  36. return "_" + android.os.Process.myPid();
  37. }
  38. private AppACache(File cacheDir, long max_size, int max_count) {
  39. if (!cacheDir.exists() && !cacheDir.mkdirs()) {
  40. throw new RuntimeException("can't make dirs in "
  41. + cacheDir.getAbsolutePath());
  42. }
  43. mCache = new ACacheManager(cacheDir, max_size, max_count);
  44. }
  45. /**
  46. * Provides a means to save a cached file before the data are available.
  47. * Since writing about the file is complete, and its close method is called,
  48. * its contents will be registered in the cache. Example of use:
  49. *
  50. * ACache cache = new ACache(this) try { OutputStream stream =
  51. * cache.put("myFileName") stream.write("some bytes".getBytes()); // now
  52. * update cache! stream.close(); } catch(FileNotFoundException e){
  53. * e.printStackTrace() }
  54. */
  55. class xFileOutputStream extends FileOutputStream {
  56. File file;
  57. public xFileOutputStream(File file) throws FileNotFoundException {
  58. super(file);
  59. this.file = file;
  60. }
  61. public void close() throws IOException {
  62. super.close();
  63. mCache.put(file);
  64. }
  65. }
  66. // =======================================
  67. // ============ String数据 读写 ==============
  68. // =======================================
  69. /**
  70. * 保存 String数据 到 缓存中
  71. *
  72. * @param key
  73. * 保存的key
  74. * @param value
  75. * 保存的String数据
  76. */
  77. public void put(String key, String value) {
  78. File file = mCache.newFile(key);
  79. BufferedWriter out = null;
  80. try {
  81. out = new BufferedWriter(new FileWriter(file), 1024);
  82. out.write(value);
  83. } catch (IOException e) {
  84. e.printStackTrace();
  85. } finally {
  86. if (out != null) {
  87. try {
  88. out.flush();
  89. out.close();
  90. } catch (IOException e) {
  91. e.printStackTrace();
  92. }
  93. }
  94. mCache.put(file);
  95. }
  96. }
  97. /**
  98. * 保存 String数据 到 缓存中
  99. *
  100. * @param key
  101. * 保存的key
  102. * @param value
  103. * 保存的String数据
  104. * @param saveTime
  105. * 保存的时间,单位:秒
  106. */
  107. public void put(String key, String value, int saveTime) {
  108. put(key, Utils.newStringWithDateInfo(saveTime, value));
  109. }
  110. /**
  111. * 读取 String数据
  112. *
  113. * @param key
  114. * @return String 数据
  115. */
  116. public String getAsString(String key) {
  117. File file = mCache.get(key);
  118. if (!file.exists())
  119. return null;
  120. boolean removeFile = false;
  121. BufferedReader in = null;
  122. try {
  123. in = new BufferedReader(new FileReader(file));
  124. String readString = "";
  125. String currentLine;
  126. while ((currentLine = in.readLine()) != null) {
  127. readString += currentLine;
  128. }
  129. if (!Utils.isDue(readString)) {
  130. return Utils.clearDateInfo(readString);
  131. } else {
  132. removeFile = true;
  133. return null;
  134. }
  135. } catch (IOException e) {
  136. e.printStackTrace();
  137. return null;
  138. } finally {
  139. if (in != null) {
  140. try {
  141. in.close();
  142. } catch (IOException e) {
  143. e.printStackTrace();
  144. }
  145. }
  146. if (removeFile)
  147. remove(key);
  148. }
  149. }
  150. // =======================================
  151. // ============= JSONObject 数据 读写 ==============
  152. // =======================================
  153. /**
  154. * 保存 JSONObject数据 到 缓存中
  155. *
  156. * @param key
  157. * 保存的key
  158. * @param value
  159. * 保存的JSON数据
  160. */
  161. public void put(String key, JSONObject value) {
  162. put(key, value.toString());
  163. }
  164. /**
  165. * 保存 JSONObject数据 到 缓存中
  166. *
  167. * @param key
  168. * 保存的key
  169. * @param value
  170. * 保存的JSONObject数据
  171. * @param saveTime
  172. * 保存的时间,单位:秒
  173. */
  174. public void put(String key, JSONObject value, int saveTime) {
  175. put(key, value.toString(), saveTime);
  176. }
  177. /**
  178. * 读取JSONObject数据
  179. *
  180. * @param key
  181. * @return JSONObject数据
  182. */
  183. public JSONObject getAsJSONObject(String key) {
  184. String JSONString = getAsString(key);
  185. try {
  186. JSONObject obj = new JSONObject(JSONString);
  187. return obj;
  188. } catch (Exception e) {
  189. e.printStackTrace();
  190. return null;
  191. }
  192. }
  193. // =======================================
  194. // ============ JSONArray 数据 读写 =============
  195. // =======================================
  196. /**
  197. * 保存 JSONArray数据 到 缓存中
  198. *
  199. * @param key
  200. * 保存的key
  201. * @param value
  202. * 保存的JSONArray数据
  203. */
  204. public void put(String key, JSONArray value) {
  205. put(key, value.toString());
  206. }
  207. /**
  208. * 保存 JSONArray数据 到 缓存中
  209. *
  210. * @param key
  211. * 保存的key
  212. * @param value
  213. * 保存的JSONArray数据
  214. * @param saveTime
  215. * 保存的时间,单位:秒
  216. */
  217. public void put(String key, JSONArray value, int saveTime) {
  218. put(key, value.toString(), saveTime);
  219. }
  220. /**
  221. * 读取JSONArray数据
  222. *
  223. * @param key
  224. * @return JSONArray数据
  225. */
  226. public JSONArray getAsJSONArray(String key) {
  227. String JSONString = getAsString(key);
  228. try {
  229. JSONArray obj = new JSONArray(JSONString);
  230. return obj;
  231. } catch (Exception e) {
  232. e.printStackTrace();
  233. return null;
  234. }
  235. }
  236. // =======================================
  237. // ============== byte 数据 读写 =============
  238. // =======================================
  239. /**
  240. * 保存 byte数据 到 缓存中
  241. *
  242. * @param key
  243. * 保存的key
  244. * @param value
  245. * 保存的数据
  246. */
  247. public void put(String key, byte[] value) {
  248. File file = mCache.newFile(key);
  249. FileOutputStream out = null;
  250. try {
  251. out = new FileOutputStream(file);
  252. out.write(value);
  253. } catch (Exception e) {
  254. e.printStackTrace();
  255. } finally {
  256. if (out != null) {
  257. try {
  258. out.flush();
  259. out.close();
  260. } catch (IOException e) {
  261. e.printStackTrace();
  262. }
  263. }
  264. mCache.put(file);
  265. }
  266. }
  267. /**
  268. * Cache for a stream
  269. *
  270. * @param key
  271. * the file name.
  272. * @return OutputStream stream for writing data.
  273. * @throws FileNotFoundException
  274. * if the file can not be created.
  275. */
  276. public OutputStream put(String key) throws FileNotFoundException {
  277. return new xFileOutputStream(mCache.newFile(key));
  278. }
  279. /**
  280. *
  281. * @param key
  282. * the file name.
  283. * @return (InputStream or null) stream previously saved in cache.
  284. * @throws FileNotFoundException
  285. * if the file can not be opened
  286. */
  287. public InputStream get(String key) throws FileNotFoundException {
  288. File file = mCache.get(key);
  289. if (!file.exists())
  290. return null;
  291. return new FileInputStream(file);
  292. }
  293. /**
  294. * 保存 byte数据 到 缓存中
  295. *
  296. * @param key
  297. * 保存的key
  298. * @param value
  299. * 保存的数据
  300. * @param saveTime
  301. * 保存的时间,单位:秒
  302. */
  303. public void put(String key, byte[] value, int saveTime) {
  304. put(key, Utils.newByteArrayWithDateInfo(saveTime, value));
  305. }
  306. /**
  307. * 获取 byte 数据
  308. *
  309. * @param key
  310. * @return byte 数据
  311. */
  312. public byte[] getAsBinary(String key) {
  313. RandomAccessFile RAFile = null;
  314. boolean removeFile = false;
  315. try {
  316. File file = mCache.get(key);
  317. if (!file.exists())
  318. return null;
  319. RAFile = new RandomAccessFile(file, "r");
  320. byte[] byteArray = new byte[(int) RAFile.length()];
  321. RAFile.read(byteArray);
  322. if (!Utils.isDue(byteArray)) {
  323. return Utils.clearDateInfo(byteArray);
  324. } else {
  325. removeFile = true;
  326. return null;
  327. }
  328. } catch (Exception e) {
  329. e.printStackTrace();
  330. return null;
  331. } finally {
  332. if (RAFile != null) {
  333. try {
  334. RAFile.close();
  335. } catch (IOException e) {
  336. e.printStackTrace();
  337. }
  338. }
  339. if (removeFile)
  340. remove(key);
  341. }
  342. }
  343. // =======================================
  344. // ============= 序列化 数据 读写 ===============
  345. // =======================================
  346. /**
  347. * 保存 Serializable数据 到 缓存中
  348. *
  349. * @param key
  350. * 保存的key
  351. * @param value
  352. * 保存的value
  353. */
  354. public void put(String key, Serializable value) {
  355. put(key, value, -1);
  356. }
  357. /**
  358. * 保存 Serializable数据到 缓存中
  359. *
  360. * @param key
  361. * 保存的key
  362. * @param value
  363. * 保存的value
  364. * @param saveTime
  365. * 保存的时间,单位:秒
  366. */
  367. public void put(String key, Serializable value, int saveTime) {
  368. ByteArrayOutputStream baos = null;
  369. ObjectOutputStream oos = null;
  370. try {
  371. baos = new ByteArrayOutputStream();
  372. oos = new ObjectOutputStream(baos);
  373. oos.writeObject(value);
  374. byte[] data = baos.toByteArray();
  375. if (saveTime != -1) {
  376. put(key, data, saveTime);
  377. } else {
  378. put(key, data);
  379. }
  380. } catch (Exception e) {
  381. e.printStackTrace();
  382. } finally {
  383. try {
  384. oos.close();
  385. } catch (IOException e) {
  386. }
  387. }
  388. }
  389. /**
  390. * 读取 Serializable数据
  391. *
  392. * @param key
  393. * @return Serializable 数据
  394. */
  395. public Object getAsObject(String key) {
  396. byte[] data = getAsBinary(key);
  397. if (data != null) {
  398. ByteArrayInputStream bais = null;
  399. ObjectInputStream ois = null;
  400. try {
  401. bais = new ByteArrayInputStream(data);
  402. ois = new ObjectInputStream(bais);
  403. Object reObject = ois.readObject();
  404. return reObject;
  405. } catch (Exception e) {
  406. e.printStackTrace();
  407. return null;
  408. } finally {
  409. try {
  410. if (bais != null)
  411. bais.close();
  412. } catch (IOException e) {
  413. e.printStackTrace();
  414. }
  415. try {
  416. if (ois != null)
  417. ois.close();
  418. } catch (IOException e) {
  419. e.printStackTrace();
  420. }
  421. }
  422. }
  423. return null;
  424. }
  425. // =======================================
  426. // ============== bitmap 数据 读写 =============
  427. // =======================================
  428. /**
  429. * 保存 bitmap 到 缓存中
  430. *
  431. * @param key
  432. * 保存的key
  433. * @param value
  434. * 保存的bitmap数据
  435. */
  436. public void put(String key, Bitmap value) {
  437. put(key, Utils.Bitmap2Bytes(value));
  438. }
  439. /**
  440. * 保存 bitmap 到 缓存中
  441. *
  442. * @param key
  443. * 保存的key
  444. * @param value
  445. * 保存的 bitmap 数据
  446. * @param saveTime
  447. * 保存的时间,单位:秒
  448. */
  449. public void put(String key, Bitmap value, int saveTime) {
  450. put(key, Utils.Bitmap2Bytes(value), saveTime);
  451. }
  452. /**
  453. * 读取 bitmap 数据
  454. *
  455. * @param key
  456. * @return bitmap 数据
  457. */
  458. public Bitmap getAsBitmap(String key) {
  459. if (getAsBinary(key) == null) {
  460. return null;
  461. }
  462. return Utils.Bytes2Bimap(getAsBinary(key));
  463. }
  464. // =======================================
  465. // ============= drawable 数据 读写 =============
  466. // =======================================
  467. /**
  468. * 保存 drawable 到 缓存中
  469. *
  470. * @param key
  471. * 保存的key
  472. * @param value
  473. * 保存的drawable数据
  474. */
  475. public void put(String key, Drawable value) {
  476. put(key, Utils.drawable2Bitmap(value));
  477. }
  478. /**
  479. * 保存 drawable 到 缓存中
  480. *
  481. * @param key
  482. * 保存的key
  483. * @param value
  484. * 保存的 drawable 数据
  485. * @param saveTime
  486. * 保存的时间,单位:秒
  487. */
  488. public void put(String key, Drawable value, int saveTime) {
  489. put(key, Utils.drawable2Bitmap(value), saveTime);
  490. }
  491. /**
  492. * 读取 Drawable 数据
  493. *
  494. * @param key
  495. * @return Drawable 数据
  496. */
  497. public Drawable getAsDrawable(String key) {
  498. if (getAsBinary(key) == null) {
  499. return null;
  500. }
  501. return Utils.bitmap2Drawable(Utils.Bytes2Bimap(getAsBinary(key)));
  502. }
  503. /**
  504. * 获取缓存文件
  505. *
  506. * @param key
  507. * @return value 缓存的文件
  508. */
  509. public File file(String key) {
  510. File f = mCache.newFile(key);
  511. if (f.exists())
  512. return f;
  513. return null;
  514. }
  515. /**
  516. * 移除某个key
  517. *
  518. * @param key
  519. * @return 是否移除成功
  520. */
  521. public boolean remove(String key) {
  522. return mCache.remove(key);
  523. }
  524. /**
  525. * 清除所有数据
  526. */
  527. public void clear() {
  528. mCache.clear();
  529. }
  530. /**
  531. * @title 缓存管理器
  532. * @version 1.0
  533. */
  534. public class ACacheManager {
  535. private final AtomicLong cacheSize;
  536. private final AtomicInteger cacheCount;
  537. private final long sizeLimit;
  538. private final int countLimit;
  539. private final Map<File, Long> lastUsageDates = Collections
  540. .synchronizedMap(new HashMap<File, Long>());
  541. protected File cacheDir;
  542. private ACacheManager(File cacheDir, long sizeLimit, int countLimit) {
  543. this.cacheDir = cacheDir;
  544. this.sizeLimit = sizeLimit;
  545. this.countLimit = countLimit;
  546. cacheSize = new AtomicLong();
  547. cacheCount = new AtomicInteger();
  548. calculateCacheSizeAndCacheCount();
  549. }
  550. /**
  551. * 计算 cacheSize和cacheCount
  552. */
  553. private void calculateCacheSizeAndCacheCount() {
  554. new Thread(new Runnable() {
  555. @Override
  556. public void run() {
  557. int size = 0;
  558. int count = 0;
  559. File[] cachedFiles = cacheDir.listFiles();
  560. if (cachedFiles != null) {
  561. for (File cachedFile : cachedFiles) {
  562. size += calculateSize(cachedFile);
  563. count += 1;
  564. lastUsageDates.put(cachedFile,
  565. cachedFile.lastModified());
  566. }
  567. cacheSize.set(size);
  568. cacheCount.set(count);
  569. }
  570. }
  571. }).start();
  572. }
  573. private void put(File file) {
  574. int curCacheCount = cacheCount.get();
  575. while (curCacheCount + 1 > countLimit) {
  576. long freedSize = removeNext();
  577. cacheSize.addAndGet(-freedSize);
  578. curCacheCount = cacheCount.addAndGet(-1);
  579. }
  580. cacheCount.addAndGet(1);
  581. long valueSize = calculateSize(file);
  582. long curCacheSize = cacheSize.get();
  583. while (curCacheSize + valueSize > sizeLimit) {
  584. long freedSize = removeNext();
  585. curCacheSize = cacheSize.addAndGet(-freedSize);
  586. }
  587. cacheSize.addAndGet(valueSize);
  588. Long currentTime = System.currentTimeMillis();
  589. file.setLastModified(currentTime);
  590. lastUsageDates.put(file, currentTime);
  591. }
  592. private File get(String key) {
  593. File file = newFile(key);
  594. Long currentTime = System.currentTimeMillis();
  595. file.setLastModified(currentTime);
  596. lastUsageDates.put(file, currentTime);
  597. return file;
  598. }
  599. private File newFile(String key) {
  600. return new File(cacheDir, key.hashCode() + "");
  601. }
  602. private boolean remove(String key) {
  603. File image = get(key);
  604. return image.delete();
  605. }
  606. private void clear() {
  607. lastUsageDates.clear();
  608. cacheSize.set(0);
  609. File[] files = cacheDir.listFiles();
  610. if (files != null) {
  611. for (File f : files) {
  612. f.delete();
  613. }
  614. }
  615. }
  616. /**
  617. * 移除旧的文件
  618. *
  619. * @return
  620. */
  621. private long removeNext() {
  622. if (lastUsageDates.isEmpty()) {
  623. return 0;
  624. }
  625. Long oldestUsage = null;
  626. File mostLongUsedFile = null;
  627. Set<Entry<File, Long>> entries = lastUsageDates.entrySet();
  628. synchronized (lastUsageDates) {
  629. for (Entry<File, Long> entry : entries) {
  630. if (mostLongUsedFile == null) {
  631. mostLongUsedFile = entry.getKey();
  632. oldestUsage = entry.getValue();
  633. } else {
  634. Long lastValueUsage = entry.getValue();
  635. if (lastValueUsage < oldestUsage) {
  636. oldestUsage = lastValueUsage;
  637. mostLongUsedFile = entry.getKey();
  638. }
  639. }
  640. }
  641. }
  642. long fileSize = calculateSize(mostLongUsedFile);
  643. if (mostLongUsedFile.delete()) {
  644. lastUsageDates.remove(mostLongUsedFile);
  645. }
  646. return fileSize;
  647. }
  648. private long calculateSize(File file) {
  649. return file.length();
  650. }
  651. }
  652. /**
  653. * @title 时间计算工具类
  654. * @version 1.0
  655. */
  656. private static class Utils {
  657. /**
  658. * 判断缓存的String数据是否到期
  659. *
  660. * @param str
  661. * @return true:到期了 false:还没有到期
  662. */
  663. private static boolean isDue(String str) {
  664. return isDue(str.getBytes());
  665. }
  666. /**
  667. * 判断缓存的byte数据是否到期
  668. *
  669. * @param data
  670. * @return true:到期了 false:还没有到期
  671. */
  672. private static boolean isDue(byte[] data) {
  673. String[] strs = getDateInfoFromDate(data);
  674. if (strs != null && strs.length == 2) {
  675. String saveTimeStr = strs[0];
  676. while (saveTimeStr.startsWith("0")) {
  677. saveTimeStr = saveTimeStr
  678. .substring(1, saveTimeStr.length());
  679. }
  680. long saveTime = Long.valueOf(saveTimeStr);
  681. long deleteAfter = Long.valueOf(strs[1]);
  682. if (System.currentTimeMillis() > saveTime + deleteAfter * 1000) {
  683. return true;
  684. }
  685. }
  686. return false;
  687. }
  688. private static String newStringWithDateInfo(int second, String strInfo) {
  689. return createDateInfo(second) + strInfo;
  690. }
  691. private static byte[] newByteArrayWithDateInfo(int second, byte[] data2) {
  692. byte[] data1 = createDateInfo(second).getBytes();
  693. byte[] retdata = new byte[data1.length + data2.length];
  694. System.arraycopy(data1, 0, retdata, 0, data1.length);
  695. System.arraycopy(data2, 0, retdata, data1.length, data2.length);
  696. return retdata;
  697. }
  698. private static String clearDateInfo(String strInfo) {
  699. if (strInfo != null && hasDateInfo(strInfo.getBytes())) {
  700. strInfo = strInfo.substring(strInfo.indexOf(mSeparator) + 1,
  701. strInfo.length());
  702. }
  703. return strInfo;
  704. }
  705. private static byte[] clearDateInfo(byte[] data) {
  706. if (hasDateInfo(data)) {
  707. return copyOfRange(data, indexOf(data, mSeparator) + 1,
  708. data.length);
  709. }
  710. return data;
  711. }
  712. private static boolean hasDateInfo(byte[] data) {
  713. return data != null && data.length > 15 && data[13] == '-'
  714. && indexOf(data, mSeparator) > 14;
  715. }
  716. private static String[] getDateInfoFromDate(byte[] data) {
  717. if (hasDateInfo(data)) {
  718. String saveDate = new String(copyOfRange(data, 0, 13));
  719. String deleteAfter = new String(copyOfRange(data, 14,
  720. indexOf(data, mSeparator)));
  721. return new String[] { saveDate, deleteAfter };
  722. }
  723. return null;
  724. }
  725. private static int indexOf(byte[] data, char c) {
  726. for (int i = 0; i < data.length; i++) {
  727. if (data[i] == c) {
  728. return i;
  729. }
  730. }
  731. return -1;
  732. }
  733. private static byte[] copyOfRange(byte[] original, int from, int to) {
  734. int newLength = to - from;
  735. if (newLength < 0)
  736. throw new IllegalArgumentException(from + " > " + to);
  737. byte[] copy = new byte[newLength];
  738. System.arraycopy(original, from, copy, 0,
  739. Math.min(original.length - from, newLength));
  740. return copy;
  741. }
  742. private static final char mSeparator = ' ';
  743. private static String createDateInfo(int second) {
  744. String currentTime = System.currentTimeMillis() + "";
  745. while (currentTime.length() < 13) {
  746. currentTime = "0" + currentTime;
  747. }
  748. return currentTime + "-" + second + mSeparator;
  749. }
  750. /*
  751. * Bitmap → byte[]
  752. */
  753. private static byte[] Bitmap2Bytes(Bitmap bm) {
  754. if (bm == null) {
  755. return null;
  756. }
  757. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  758. bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
  759. return baos.toByteArray();
  760. }
  761. /*
  762. * byte[] → Bitmap
  763. */
  764. private static Bitmap Bytes2Bimap(byte[] b) {
  765. if (b.length == 0) {
  766. return null;
  767. }
  768. return BitmapFactory.decodeByteArray(b, 0, b.length);
  769. }
  770. /*
  771. * Drawable → Bitmap
  772. */
  773. private static Bitmap drawable2Bitmap(Drawable drawable) {
  774. if (drawable == null) {
  775. return null;
  776. }
  777. // 取 drawable 的长宽
  778. int w = drawable.getIntrinsicWidth();
  779. int h = drawable.getIntrinsicHeight();
  780. // 取 drawable 的颜色格式
  781. Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
  782. : Bitmap.Config.RGB_565;
  783. // 建立对应 bitmap
  784. Bitmap bitmap = Bitmap.createBitmap(w, h, config);
  785. // 建立对应 bitmap 的画布
  786. Canvas canvas = new Canvas(bitmap);
  787. drawable.setBounds(0, 0, w, h);
  788. // 把 drawable 内容画到画布中
  789. drawable.draw(canvas);
  790. return bitmap;
  791. }
  792. /*
  793. * Bitmap → Drawable
  794. */
  795. @SuppressWarnings("deprecation")
  796. private static Drawable bitmap2Drawable(Bitmap bm) {
  797. if (bm == null) {
  798. return null;
  799. }
  800. return new BitmapDrawable(bm);
  801. }
  802. }
复制代码

}

终点站

好了,终点站到了,如果对本次旅途满意的话,请给五星好评哦,没关注的小伙伴轻轻点个上方的关注,毕竟老司机牺牲了很多时间才换来这么一份工具类,如果该工具类依赖其他工具类,都可以在我的史上最全的常用开发工具类收集(持续更新中)中找到。



回复

使用道具 举报