1. 对图片本身进行操作

尽量不要使用 setImageBitmap、setImageResource、 BitmapFactory.decodeResource 来设置一张大图,因为这些方法在完成 decode 后,最终都是通过 Java 层的 createBitmap 来完成的,需要消耗更多内存。因此,改用先通过 BitmapFactory.decodeStream 方法,创建出一个 bitmap,再将其设为 ImageView 的 source,decodeStream 最大的秘密在于其直接调用 JNI>>nativeDecodeAsset() 来完成 decode,无需再使用 Java 层的 createBitmap,从而节省了 Java 层的空间。如果在读取时加上图片的 Config 参数,可以更有效的减少加载的内存,从而更有效阻止抛出内存异常。另外,decodeStream 直接拿图片来读取字节码了,不会根据机器的各种分辨率来自动适应,使用了 decodeStream 之后,需要在 hdpi 和 mdpi,ldpi 中配置相应的图片资源, 否则在不同分辨率机器上都是同样大小(像素点数量),显示出来的大小就不对了。

InputStream is = this.getResources().openRawResource(R.drawable.pic);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 2;
Bitmap btp =BitmapFactory.decodeStream(is,null,options);

以上代码即是读取 drawable 下名为 pic 图片的缩略图,长度、宽度都只有原图片的 1/2。图片大小减少,占用的内存自然也变小了。这么做的弊端是图片质量变差,inSampleSize 的值越大,图片的质量就越差。由于各手机厂商缩放图片的算法不同,在不同手机上的缩放图片质量可能会不同。

2. 调用图片的 recycle() 方法

if(!bmp.isRecycle() ){
bmp.recycle() // 回收图片所占的内存
system.gc() // 提醒系统及时回收
}

这种方法其实不是真正降低图片内存的方法。主要目的是标记图片对象,方便回收图片对象的本地数据。图片对象的本地数据占用的内存最大,而且与程序 Java 部分的内存是分开计算的。所以经常出现 Java heap 足够使用,而图片发生 OutOfMemoryError 的情况。在图片不使用时调用该方法,可以有效降低图片本地数据的峰值,从而减少 OutOfMemoryError 的概率。不过调用了 recycle() 的图片对象处于“废弃”状态,调用时会造成程序错误。所以在无法保证该图片对象绝对不会被再次调用的情况下,不建议使用该方法。特别要注意已经用 setImageBitmap(Bitmap 
img) 方法分配给控件的图片对象,可能会被系统类库调用,造成程序错误。

3. 以最省内存的方式读取本地资源的图片

/**
* 以最省内存的方式读取本地资源的图片
*/
public static Bitmap readBitMap(Context context, int resId){
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
// 获取资源图片
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is,null,opt);
}

Android 中加载图片的颜色模式有四种,分别是:ALPHA_8:每个像素占用 1byte 内存、ARGB_4444:每个像素占用 2byte 内存、ARGB_8888:每个像素占用 4byte 内存、RGB_565:每个像素占用 2byte 内存。Android默认的颜色模式为ARGB_8888,这个颜色模式色彩最细腻,显示质量最高。但同样的,占用的内存也最大。以上代码即是将图片资源以 RGB_565 (或以 ARGB_4444)模式读出。内存减少虽然不如第一种方法明显,但是对于大多数图片,看不出与 ARGB_8888 模式有什么差别。不过在读取有渐变效果的图片时,可能有颜色条出现。另外,会影响图片的特效处理。

4. 使用 Matrix 对象放大的图片如何更改颜色模式:

虽然使用 Matrix 对象放大图片,必定会耗费更多的内存,但有时候也不得不这样做。放大后的图片使用的 ARGB_8888 颜色模式,就算原图片是ARGB_4444 颜色模式也一样,而且没有办法在放大时直接指定颜色模式。可以采用以下办法更改图片颜色模式。

Matrix matrix = new Matrix();
float newWidth = 200; // 图片放大后的宽度
float newHeight = 300; // 图片放大后的长度
matrix.postScale(newWidth / img.getWidth(), newHeight/ img.getHeight());
Bitmap img1 = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);// 得到放大图片
img2 = img1.copy(Bitmap.Config.ARGB_4444, false); // 得到 ARGB_4444 颜色模式的图片
img = null;
img1 = null;

这里比起本来的图片额外生成了一个图片对象 img1。然则体系会主动收受接管 img1,所以实际内存还是削减了。

归结起来还是以缩略图模式读取图片和削减图片中每个像素占用的内存最为有效。 这两种办法固然有效,然则也有各自的弊病。实际开辟中还是应当按照景象酌情应用。最王道的办法,还是避免垃圾对象的产生。例如在 ListView 的应用中,复用 convertView 等。若是应用 AsyncTask 加载图片,要及时将引用的 ImageView 对象置为 null。因为 AsyncTask 是用线程池实现的,所以此中引用的对象可能会拥有很长的生命周期,造成 GC 无法开释。我还是信赖 Android 的内存收受接管机制的,recycle 什么的固然必然程度上有效,但总感觉不合适 Java 内存收受接管的原则。

在网上调查了图片压缩的方法并实装后,大致上可以认为有两类压缩:质量压缩(不改变图片的尺寸)和尺寸压缩(相当于是像素上的压缩);质量压缩一般可用于上传大图前的处理,这样就可以节省一定的流量,毕竟现在的手机拍照都能达到3M左右了,尺寸压缩一般可用于生成缩略图。
两种方法都实装在了我的项目中,结果却发现在质量压缩的模块中,本来1.9M的图片压缩后反而变成3M多了,很是奇怪,再做了进一步调查终于知道原因了。下面这个博客说的比较清晰:

android图片压缩总结

总结来看,图片有三种存在形式:硬盘上时是file,网络传输时是stream,内存中是stream或bitmap,所谓的质量压缩,它其实只能实现对file的影响,你可以把一个file转成bitmap再转成file,或者直接将一个bitmap转成file时,这个最终的file是被压缩过的,但是中间的bitmap并没有被压缩(或者说几乎没有被压缩,我不确定),因为bigmap在内存中的大小是按像素计算的,也就是width * height,对于质量压缩,并不会改变图片的像素,所以就算质量被压缩了,但是bitmap在内存的占有率还是没变小,但你做成file时,它确实变小了;

而尺寸压缩由于是减小了图片的像素,所以它直接对bitmap产生了影响,当然最终的file也是相对的变小了;

最后把自己总结的工具类贴出来:

  1. import java.io.ByteArrayInputStream;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import android.graphics.Bitmap;
  8. import android.graphics.Bitmap.Config;
  9. import android.graphics.BitmapFactory;
  10. /**
  11. * Image compress factory class
  12. *
  13. * @author
  14. *
  15. */
  16. public class ImageFactory {
  17. /**
  18. * Get bitmap from specified image path
  19. *
  20. * @param imgPath
  21. * @return
  22. */
  23. public Bitmap getBitmap(String imgPath) {
  24. // Get bitmap through image path
  25. BitmapFactory.Options newOpts = new BitmapFactory.Options();
  26. newOpts.inJustDecodeBounds = false;
  27. newOpts.inPurgeable = true;
  28. newOpts.inInputShareable = true;
  29. // Do not compress
  30. newOpts.inSampleSize = 1;
  31. newOpts.inPreferredConfig = Config.RGB_565;
  32. return BitmapFactory.decodeFile(imgPath, newOpts);
  33. }
  34. /**
  35. * Store bitmap into specified image path
  36. *
  37. * @param bitmap
  38. * @param outPath
  39. * @throws FileNotFoundException
  40. */
  41. public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException {
  42. FileOutputStream os = new FileOutputStream(outPath);
  43. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
  44. }
  45. /**
  46. * Compress image by pixel, this will modify image width/height.
  47. * Used to get thumbnail
  48. *
  49. * @param imgPath image path
  50. * @param pixelW target pixel of width
  51. * @param pixelH target pixel of height
  52. * @return
  53. */
  54. public Bitmap ratio(String imgPath, float pixelW, float pixelH) {
  55. BitmapFactory.Options newOpts = new BitmapFactory.Options();
  56. // 开始读入图片,此时把options.inJustDecodeBounds 设回true,即只读边不读内容
  57. newOpts.inJustDecodeBounds = true;
  58. newOpts.inPreferredConfig = Config.RGB_565;
  59. // Get bitmap info, but notice that bitmap is null now
  60. Bitmap bitmap = BitmapFactory.decodeFile(imgPath,newOpts);
  61. newOpts.inJustDecodeBounds = false;
  62. int w = newOpts.outWidth;
  63. int h = newOpts.outHeight;
  64. // 想要缩放的目标尺寸
  65. float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了
  66. float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了
  67. // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
  68. int be = 1;//be=1表示不缩放
  69. if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
  70. be = (int) (newOpts.outWidth / ww);
  71. } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
  72. be = (int) (newOpts.outHeight / hh);
  73. }
  74. if (be <= 0) be = 1;
  75. newOpts.inSampleSize = be;//设置缩放比例
  76. // 开始压缩图片,注意此时已经把options.inJustDecodeBounds 设回false了
  77. bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
  78. // 压缩好比例大小后再进行质量压缩
  79. //        return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除
  80. return bitmap;
  81. }
  82. /**
  83. * Compress image by size, this will modify image width/height.
  84. * Used to get thumbnail
  85. *
  86. * @param image
  87. * @param pixelW target pixel of width
  88. * @param pixelH target pixel of height
  89. * @return
  90. */
  91. public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
  92. ByteArrayOutputStream os = new ByteArrayOutputStream();
  93. image.compress(Bitmap.CompressFormat.JPEG, 100, os);
  94. if( os.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
  95. os.reset();//重置baos即清空baos
  96. image.compress(Bitmap.CompressFormat.JPEG, 50, os);//这里压缩50%,把压缩后的数据存放到baos中
  97. }
  98. ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
  99. BitmapFactory.Options newOpts = new BitmapFactory.Options();
  100. //开始读入图片,此时把options.inJustDecodeBounds 设回true了
  101. newOpts.inJustDecodeBounds = true;
  102. newOpts.inPreferredConfig = Config.RGB_565;
  103. Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
  104. newOpts.inJustDecodeBounds = false;
  105. int w = newOpts.outWidth;
  106. int h = newOpts.outHeight;
  107. float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了
  108. float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了
  109. //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
  110. int be = 1;//be=1表示不缩放
  111. if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
  112. be = (int) (newOpts.outWidth / ww);
  113. } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
  114. be = (int) (newOpts.outHeight / hh);
  115. }
  116. if (be <= 0) be = 1;
  117. newOpts.inSampleSize = be;//设置缩放比例
  118. //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
  119. is = new ByteArrayInputStream(os.toByteArray());
  120. bitmap = BitmapFactory.decodeStream(is, null, newOpts);
  121. //压缩好比例大小后再进行质量压缩
  122. //      return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除
  123. return bitmap;
  124. }
  125. /**
  126. * Compress by quality,  and generate image to the path specified
  127. *
  128. * @param image
  129. * @param outPath
  130. * @param maxSize target will be compressed to be smaller than this size.(kb)
  131. * @throws IOException
  132. */
  133. public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException {
  134. ByteArrayOutputStream os = new ByteArrayOutputStream();
  135. // scale
  136. int options = 100;
  137. // Store the bitmap into output stream(no compress)
  138. image.compress(Bitmap.CompressFormat.JPEG, options, os);
  139. // Compress by loop
  140. while ( os.toByteArray().length / 1024 > maxSize) {
  141. // Clean up os
  142. os.reset();
  143. // interval 10
  144. options -= 10;
  145. image.compress(Bitmap.CompressFormat.JPEG, options, os);
  146. }
  147. // Generate compressed image file
  148. FileOutputStream fos = new FileOutputStream(outPath);
  149. fos.write(os.toByteArray());
  150. fos.flush();
  151. fos.close();
  152. }
  153. /**
  154. * Compress by quality,  and generate image to the path specified
  155. *
  156. * @param imgPath
  157. * @param outPath
  158. * @param maxSize target will be compressed to be smaller than this size.(kb)
  159. * @param needsDelete Whether delete original file after compress
  160. * @throws IOException
  161. */
  162. public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException {
  163. compressAndGenImage(getBitmap(imgPath), outPath, maxSize);
  164. // Delete original file
  165. if (needsDelete) {
  166. File file = new File (imgPath);
  167. if (file.exists()) {
  168. file.delete();
  169. }
  170. }
  171. }
  172. /**
  173. * Ratio and generate thumb to the path specified
  174. *
  175. * @param image
  176. * @param outPath
  177. * @param pixelW target pixel of width
  178. * @param pixelH target pixel of height
  179. * @throws FileNotFoundException
  180. */
  181. public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException {
  182. Bitmap bitmap = ratio(image, pixelW, pixelH);
  183. storeImage( bitmap, outPath);
  184. }
  185. /**
  186. * Ratio and generate thumb to the path specified
  187. *
  188. * @param image
  189. * @param outPath
  190. * @param pixelW target pixel of width
  191. * @param pixelH target pixel of height
  192. * @param needsDelete Whether delete original file after compress
  193. * @throws FileNotFoundException
  194. */
  195. public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException {
  196. Bitmap bitmap = ratio(imgPath, pixelW, pixelH);
  197. storeImage( bitmap, outPath);
  198. // Delete original file
  199. if (needsDelete) {
  200. File file = new File (imgPath);
  201. if (file.exists()) {
  202. file.delete();
  203. }
  204. }
  205. }
  206. }
 
 
如果上面的工具类不满足你,那么看看下面的方法。
 
一、图片质量压缩
  1. /**
  2. * 质量压缩方法
  3. *
  4. * @param image
  5. * @return
  6. */
  7. public static Bitmap compressImage(Bitmap image) {
  8. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  9. image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
  10. int options = 90;
  11. while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
  12. baos.reset(); // 重置baos即清空baos
  13. image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中
  14. options -= 10;// 每次都减少10
  15. }
  16. ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
  17. Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
  18. return bitmap;
  19. }

二、按比例大小压缩 (路径获取图片)

 
  1. /**
  2. * 图片按比例大小压缩方法
  3. *
  4. * @param srcPath (根据路径获取图片并压缩)
  5. * @return
  6. */
  7. public static Bitmap getimage(String srcPath) {
  8. BitmapFactory.Options newOpts = new BitmapFactory.Options();
  9. // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
  10. newOpts.inJustDecodeBounds = true;
  11. Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空
  12. newOpts.inJustDecodeBounds = false;
  13. int w = newOpts.outWidth;
  14. int h = newOpts.outHeight;
  15. // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
  16. float hh = 800f;// 这里设置高度为800f
  17. float ww = 480f;// 这里设置宽度为480f
  18. // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
  19. int be = 1;// be=1表示不缩放
  20. if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
  21. be = (int) (newOpts.outWidth / ww);
  22. } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
  23. be = (int) (newOpts.outHeight / hh);
  24. }
  25. if (be <= 0)
  26. be = 1;
  27. newOpts.inSampleSize = be;// 设置缩放比例
  28. // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
  29. bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
  30. return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
  31. }

三、按比例大小压缩 (Bitmap)

 
  1. /**
  2. * 图片按比例大小压缩方法
  3. *
  4. * @param image (根据Bitmap图片压缩)
  5. * @return
  6. */
  7. public static Bitmap compressScale(Bitmap image) {
  8. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  9. image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
  10. // 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
  11. if (baos.toByteArray().length / 1024 > 1024) {
  12. baos.reset();// 重置baos即清空baos
  13. image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%,把压缩后的数据存放到baos中
  14. }
  15. ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
  16. BitmapFactory.Options newOpts = new BitmapFactory.Options();
  17. // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
  18. newOpts.inJustDecodeBounds = true;
  19. Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
  20. newOpts.inJustDecodeBounds = false;
  21. int w = newOpts.outWidth;
  22. int h = newOpts.outHeight;
  23. Log.i(TAG, w + "---------------" + h);
  24. // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为
  25. // float hh = 800f;// 这里设置高度为800f
  26. // float ww = 480f;// 这里设置宽度为480f
  27. float hh = 512f;
  28. float ww = 512f;
  29. // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
  30. int be = 1;// be=1表示不缩放
  31. if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
  32. be = (int) (newOpts.outWidth / ww);
  33. } else if (w < h && h > hh) { // 如果高度高的话根据高度固定大小缩放
  34. be = (int) (newOpts.outHeight / hh);
  35. }
  36. if (be <= 0)
  37. be = 1;
  38. newOpts.inSampleSize = be; // 设置缩放比例
  39. // newOpts.inPreferredConfig = Config.RGB_565;//降低图片从ARGB888到RGB565
  40. // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
  41. isBm = new ByteArrayInputStream(baos.toByteArray());
  42. bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
  43. return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
  44. //return bitmap;
  45. }
 
 
 
--------------------------------------------------------------------------------------------------------------------------------
 
分享个按照图片尺寸压缩:
 
  1. public static void compressPicture(String srcPath, String desPath) {
  2. FileOutputStream fos = null;
  3. BitmapFactory.Options op = new BitmapFactory.Options();
  4. // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
  5. op.inJustDecodeBounds = true;
  6. Bitmap bitmap = BitmapFactory.decodeFile(srcPath, op);
  7. op.inJustDecodeBounds = false;
  8. // 缩放图片的尺寸
  9. float w = op.outWidth;
  10. float h = op.outHeight;
  11. float hh = 1024f;//
  12. float ww = 1024f;//
  13. // 最长宽度或高度1024
  14. float be = 1.0f;
  15. if (w > h && w > ww) {
  16. be = (float) (w / ww);
  17. } else if (w < h && h > hh) {
  18. be = (float) (h / hh);
  19. }
  20. if (be <= 0) {
  21. be = 1.0f;
  22. }
  23. op.inSampleSize = (int) be;// 设置缩放比例,这个数字越大,图片大小越小.
  24. // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
  25. bitmap = BitmapFactory.decodeFile(srcPath, op);
  26. int desWidth = (int) (w / be);
  27. int desHeight = (int) (h / be);
  28. bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
  29. try {
  30. fos = new FileOutputStream(desPath);
  31. if (bitmap != null) {
  32. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
  33. }
  34. } catch (FileNotFoundException e) {
  35. e.printStackTrace();
  36. }
  37. }

需要注意两个问题:

一、调用getDrawingCache()前先要测量,否则的话得到的bitmap为null,这个我在OnCreate()、OnStart()、OnResume()方法里都试验过。

二、当调用bitmap.compress(CompressFormat.JPEG, 100, fos);保存为图片时发现图片背景为黑色,如下图:

这时只需要改成用png保存就可以了,bitmap.compress(CompressFormat.PNG, 100, fos);,如下图:

在实际开发中,有时候我们需求将文件转换为字符串,然后作为参数进行上传。

必备工具类图片bitmap转成字符串string与String字符串转换为bitmap图片格式

  1. import android.graphics.Bitmap;
  2. import android.graphics.BitmapFactory;
  3. import android.util.Base64;
  4. import java.io.ByteArrayOutputStream;
  5. /**
  6. *
  7. *
  8. * 功能描述:Android开发之常用必备工具类图片bitmap转成字符串string与String字符串转换为bitmap图片格式
  9. */
  10. public class BitmapAndStringUtils {
  11. /**
  12. * 图片转成string
  13. *
  14. * @param bitmap
  15. * @return
  16. */
  17. public static String convertIconToString(Bitmap bitmap)
  18. {
  19. ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
  20. bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
  21. byte[] appicon = baos.toByteArray();// 转为byte数组
  22. return Base64.encodeToString(appicon, Base64.DEFAULT);
  23. }
  24. /**
  25. * string转成bitmap
  26. *
  27. * @param st
  28. */
  29. public static Bitmap convertStringToIcon(String st)
  30. {
  31. // OutputStream out;
  32. Bitmap bitmap = null;
  33. try
  34. {
  35. // out = new FileOutputStream("/sdcard/aa.jpg");
  36. byte[] bitmapArray;
  37. bitmapArray = Base64.decode(st, Base64.DEFAULT);
  38. bitmap =
  39. BitmapFactory.decodeByteArray(bitmapArray, 0,
  40. bitmapArray.length);
  41. // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
  42. return bitmap;
  43. }
  44. catch (Exception e)
  45. {
  46. return null;
  47. }
  48. }
  49. }

如果你的图片是File文件,可以用下面代码:

  1. /**
  2. * 图片文件转换为指定编码的字符串
  3. *
  4. * @param imgFile  图片文件
  5. */
  6. public static String file2String(File imgFile) {
  7. InputStream in = null;
  8. byte[] data = null;
  9. //读取图片字节数组
  10. try{
  11. in = new FileInputStream(imgFile);
  12. data = new byte[in.available()];
  13. in.read(data);
  14. in.close();
  15. } catch (IOException e){
  16. e.printStackTrace();
  17. }
  18. //对字节数组Base64编码
  19. BASE64Encoder encoder = new BASE64Encoder();
  20. String result = encoder.encode(data);
  21. return result;//返回Base64编码过的字节数组字符串
  22. }

Android 编程下图片的内存优化的更多相关文章

  1. Android 中对于图片的内存优化方法

    Android 中对于图片的内存优化方法,需要的朋友可以参考一下     1. 对图片本身进行操作 尽量不要使用 setImageBitmap.setImageResource. BitmapFact ...

  2. 【转】Android开发之Bitmap的内存优化详解

    本文来源:转载自: http://mobile.51cto.com/abased-410796.htm 在Android应用里,最耗费内存的就是图片资源.而且在Android系统中,读取位图Bitma ...

  3. 图片--Android加载图片导致内存溢出(Out of Memory异常)

    Android在加载大背景图或者大量图片时,经常导致内存溢出(Out of Memory  Error),本文根据我处理这些问题的经历及其它开发者的经验,整理解决方案如下(部分代码及文字出处无法考证) ...

  4. 关于Android应用中图片占用内存浅谈

    从事过移动端应用开发的童鞋应该都清楚,内存是非常宝贵的资源.如果能很好的利用有限的内存,对应用性能的提升会有很大的帮助.在实际应用开发中图片内存占整个应用非常大的比重,我们只有了解图片是如何加载到内存 ...

  5. Android加载图片导致内存溢出(Out of Memory异常)

    Android在加载大背景图或者大量图片时,经常导致内存溢出(Out of Memory  Error),本文根据我处理这些问题的经历及其它开发者的经验,整理解决方案如下(部分代码及文字出处无法考证) ...

  6. Android 多图,大图内存优化

    策略: 1. 图片压缩 如果所需尺寸大于图片原始尺寸,可以压缩图片节省内存. 2. 图片缓存 每个图片加载时都会生成一个 Bitmap.把这些 Bitmap 缓存起来以重用相同的图片,避免重复创建. ...

  7. Android之——图片的内存优化

    转载请注明出处:http://blog.csdn.net/l1028386804/article/details/46972817 1. 对图片本身进行操作 尽量不要使用 setImageBitmap ...

  8. Android 编程下通过 zipalign 对 APK 文件进行优化

    zipalign zipalign is an archive alignment tool that provides important optimization to Android appli ...

  9. Android 编程下背景图片适配工具类

    package cn.sunzn.util; import android.content.Context; import android.graphics.Bitmap; import androi ...

随机推荐

  1. 算法训练 区间k大数查询

    http://lx.lanqiao.org/problem.page?gpid=T11 算法训练 区间k大数查询   时间限制:1.0s   内存限制:256.0MB        问题描述 给定一个 ...

  2. php 迭代器

    迭代器(Iterator)模式,又叫做游标(Cursor)模式.GOF给出的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部细节. 百度百科: http: ...

  3. Fresco源码解析 - DataSource怎样存储数据

    Fresco源码解析 - DataSource怎样存储数据 datasource是一个独立的 package,与FB导入的guava包都在同一个工程内 - fbcore. datasource的类关系 ...

  4. JAVA面试题之实现字符串的倒序输出

    package shb.java.demo; public class MyTest { public static void main(String[] args) { String string ...

  5. EBS R12版 GL追溯到各个模块

    应收.应付.收款.付款等单据都可以生成ERP的日记帐,那么这些模块的关系是如何关联的呢,我们将会解决这个问题. 各个模块与总帐模块的关系,主要是通过子分类帐来进行关联的. 下面的SQL就是总帐与子分类 ...

  6. backend flow

    在PD之后,netlist中会多出很多DCAP元件(去耦电容,减少IR-Drop)或者filter cell(保证芯片均匀度要求) 还有一些antenna cell也就是一些diode用来泻流,防止天 ...

  7. PAT乙级 1003. 我要通过!(20)

    答案正确”是自动判题系统给出的最令人欢喜的回复.本题属于PAT的“答案正确”大派送 —— 只要读入的字符串满足下列条件,系统就输出“答案正确”,否则输出“答案错误”. 得到“答案正确”的条件是: 1. ...

  8. 9. 星际争霸之php设计模式--代理模式

    题记==============================================================================本php设计模式专辑来源于博客(jymo ...

  9. YUI Reset CSS (学习摘抄)

    正在使用CSS的你,用过CSS Reset吗?当然,或许你用了,却不知道正在用,比如你可能用到: *{    margin: 0;    border: 0;    padding: 0;   } 这 ...

  10. Date() 及其 如何验证用户输入的日期是合法的

    1.var someDate = new Date(Date.parse("May 25, 2004"));   <=>  var someDate = new Dat ...