Bitmap类用法 详细说明
发布日期:2021-11-12 07:57:26 浏览次数:29 分类:技术文章

本文共 10779 字,大约阅读时间需要 35 分钟。

原文地址:http://blog.csdn.net/ymangu666/article/details/37729109

1.  BitMap类
public void recycle()——回收位图占用的内存空间,把位图标记为Dead 

public final boolean isRecycled() ——判断位图内存是否已释放 
public final int getWidth()——获取位图的宽度 
public final int getHeight()——获取位图的高度 
public final boolean isMutable()——图片是否可修改 
public int getScaledWidth(Canvas canvas)——获取指定密度转换后的图像的宽度 
public int getScaledHeight(Canvas canvas)——获取指定密度转换后的图像的高度 
public boolean compress(CompressFormat format, int quality, OutputStream stream)——按指定的图片格式以及画质,将图片转换为输出流。 
format:Bitmap.CompressFormat.PNG或Bitmap.CompressFormat.JPEG 
quality:画质,0-100.0表示最低画质压缩,100以最高画质压缩。对于PNG等无损格式的图片,会忽略此项设置。 
常用的静态方法: 
public static Bitmap createBitmap(Bitmap src) ——以src为原图生成不可变得新图像 
public static Bitmap createScaledBitmap(Bitmap src, int dstWidth, 
            int dstHeight, boolean filter)——以src为原图,创建新的图像,指定新图像的高宽以及是否可变。 
public static Bitmap createBitmap(int width, int height, Config config)——创建指定格式、大小的位图 
public static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height)以source为原图,创建新的图片,指定起始坐标以及新图像的高宽。 
2. BitmapFactory工厂类:
Option 参数类: 
public boolean inJustDecodeBounds——如果设置为true,不获取图片,不分配内存,但会返回图片的高度宽度信息。 
public int inSampleSize——图片缩放的倍数。如果设为4,则宽和高都为原来的1/4,则图是原来的1/16。 
public int outWidth——获取图片的宽度值 
public int outHeight——获取图片的高度值 
public int inDensity——用于位图的像素压缩比 
public int inTargetDensity——用于目标位图的像素压缩比(要生成的位图) 
public boolean inScaled——设置为true时进行图片压缩,从inDensity到inTargetDensity。
使用BitmapFactory  可从资源files, streams, and byte-arrays中解码生成Bitmap对象。
读取一个文件路径得到一个位图。如果指定文件为空或者不能解码成文件,则返回NULL。 
public static Bitmap decodeFile(String pathName, Options opts) 
public static Bitmap decodeFile(String pathName) 
读取一个资源文件得到一个位图。如果位图数据不能被解码,或者opts参数只请求大小信息时,则返回NuLL。 
(即当Options.inJustDecodeBounds=true,只请求图片的大小信息。) 
public static Bitmap decodeResource(Resources res, int id) 
public static Bitmap decodeResource(Resources res, int id, Options opts) 
从输入流中解码位图 
public static Bitmap decodeStream(InputStream is) 
从字节数组中解码生成不可变的位图 
public static Bitmap decodeByteArray(byte[] data, int offset, int length) 
BitmapDrawable类:继承于Drawable,你可以从文件路径、输入流、XML文件以及Bitmap中创建。 
常用的构造函数: 
Resources res=getResources();//获取资源 
public BitmapDrawable(Resources res)——创建一个空的drawable。(Response用来指定初始时所用的像素密度)替代public BitmapDrawable()方法(此方法不处理像素密度) 
public BitmapDrawable(Resources res, Bitmap bitmap)——Create drawable from a bitmap 
public BitmapDrawable(Resources res, String filepath)——Create a drawable by opening a given file path and decoding the bitmap. 
public BitmapDrawable(Resources res, java.io.InputStream is)——Create a drawable by decoding a bitmap from the given input stream. 

2).显示Bitmap
2.1) 使用Canvas类显示位图

[java]   
 
  1. public class Main extends Activity {          
  2.     @Override    
  3.     public void onCreate(Bundle savedInstanceState) {     
  4.         super.onCreate(savedInstanceState);     
  5.         setContentView(new Panel(this));     
  6.     }            
  7.     class Panel extends View{              
  8.         public Panel(Context context) {       
  9.             super(context);      
  10.         }           
  11.         public void onDraw(Canvas canvas){       
  12.             Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pic180);       
  13.             canvas.drawColor(Color.BLACK);       
  14.             canvas.drawBitmap(bmp, 1010null);       
  15.         }       
  16.     }      
  17. }  
2.2) 通过BitmapDrawable显示位图

[java]   
 
  1. // 获取位图   
  2.  Bitmap bmp=BitmapFactory.decodeResource(res, R.drawable.pic180);   
  3.  // 转换为BitmapDrawable对象   
  4.  BitmapDrawable bmpDraw=new BitmapDrawable(bmp);   
  5.  // 显示位图   
  6.  ImageView iv2 = (ImageView)findViewById(R.id.ImageView02);   
  7.  iv2.setImageDrawable(bmpDraw);   
  摘自:http://www.myexception.cn/android/1353713.html 


Android中Bitmap的常见操作整理一览,需要的朋友可以参考下
摘自:

[java]   
 
  1. //方法:   
  2. //1 生成圆角Bitmap图片   
  3. //2 生成Bitmap缩量图   
  4. //3 压缩图片场长宽以及kB   
  5. //注意:   
  6. //以上代码,测试其中一个方法时最好注释掉其余的代码   
  7. public class MainActivity extends Activity {   
  8. private ImageView imageView;   
  9. private Bitmap copyRawBitmap1;   
  10. private Bitmap copyRawBitmap2;   
  11. private Bitmap copyRawBitmap3;   
  12. @Override   
  13. public void onCreate(Bundle savedInstanceState) {   
  14. super.onCreate(savedInstanceState);   
  15. setContentView(R.layout.main);   
  16. imageView = (ImageView) findViewById(R.id.imageView);   
  17. //第一种方式:从资源文件中得到图片   
  18. Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.haha);   
  19. copyRawBitmap1=rawBitmap;   
  20. copyRawBitmap2=rawBitmap;   
  21. copyRawBitmap3=rawBitmap;   
  22. //第二种方式:从SD卡中得到图片(方法1)   
  23. String SDCarePath=Environment.getExternalStorageDirectory().toString();   
  24. String filePath=SDCarePath+"/"+"haha.jpg";   
  25. Bitmap rawBitmap1 = BitmapFactory.decodeFile(filePath, null);   
  26. //第二种方式:从SD卡中得到图片(方法2)   
  27. InputStream inputStream=getBitmapInputStreamFromSDCard("haha.jpg");   
  28. Bitmap rawBitmap2 = BitmapFactory.decodeStream(inputStream);   
  29.   
  30. //————>以下为将设置图片的圆角   
  31. Bitmap roundCornerBitmap=this.toRoundCorner(rawBitmap, 40);   
  32. imageView.setImageBitmap(roundCornerBitmap);   
  33. //————>以上为将设置图片的圆角   
  34.   
  35. //————>以下为将图片高宽和的大小kB压缩   
  36. // 得到图片原始的高宽   
  37. int rawHeight = rawBitmap.getHeight();   
  38. int rawWidth = rawBitmap.getWidth();   
  39. // 设定图片新的高宽   
  40. int newHeight = 500;   
  41. int newWidth = 500;   
  42. // 计算缩放因子   
  43. float heightScale = ((float) newHeight) / rawHeight;   
  44. float widthScale = ((float) newWidth) / rawWidth;   
  45. // 新建立矩阵   
  46. Matrix matrix = new Matrix();   
  47. matrix.postScale(heightScale, widthScale);   
  48. // 设置图片的旋转角度   
  49. //matrix.postRotate(-30);   
  50. // 设置图片的倾斜   
  51. //matrix.postSkew(0.1f, 0.1f);   
  52. //将图片大小压缩   
  53. //压缩后图片的宽和高以及kB大小均会变化   
  54. Bitmap newBitmap = Bitmap.createBitmap(rawBitmap, 00, rawWidth,rawWidth, matrix, true);   
  55. // 将Bitmap转换为Drawable   
  56. Drawable newBitmapDrawable = new BitmapDrawable(newBitmap);   
  57. imageView.setImageDrawable(newBitmapDrawable);   
  58. //然后将Bitmap保存到SDCard中,方便于原图片的比较   
  59. this.compressAndSaveBitmapToSDCard(newBitmap, "xx100.jpg"80);   
  60. //问题:   
  61. //原图大小为625x690 90.2kB   
  62. //如果设置图片500x500 压缩后大小为171kB.即压缩后kB反而变大了.   
  63. //原因是将:compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream);   
  64. //第二个参数quality设置得有些大了(比如100).   
  65. //常用的是80,刚设100太大了造成的.   
  66. //————>以上为将图片高宽和的大小kB压缩   
  67.   
  68.   
  69. //————>以下为将图片的kB压缩,宽高不变   
  70. this.compressAndSaveBitmapToSDCard(copyRawBitmap1,"0011fa.jpg",80);   
  71. //————>以上为将图片的kB压缩,宽高不变   
  72.   
  73. //————>以下为获取SD卡图片的缩略图方法1   
  74. String SDCarePath1=Environment.getExternalStorageDirectory().toString();   
  75. String filePath1=SDCarePath1+"/"+"haha.jpg";   
  76. Bitmap bitmapThumbnail1=this.getBitmapThumbnail(filePath1);   
  77. imageView.setImageBitmap(bitmapThumbnail1);   
  78. //————>以上为获取SD卡图片的缩略图方法1   
  79.   
  80. //————>以下为获取SD卡图片的缩略图方法2   
  81. String SDCarePath2=Environment.getExternalStorageDirectory().toString();   
  82. String filePath2=SDCarePath2+"/"+"haha.jpg";   
  83. Bitmap tempBitmap=BitmapFactory.decodeFile(filePath2);   
  84. Bitmap bitmapThumbnail2=ThumbnailUtils.extractThumbnail(tempBitmap, 100100);   
  85. imageView.setImageBitmap(bitmapThumbnail2);   
  86. //————>以上为获取SD卡图片的缩略图方法2   
  87.   
  88. }   
  89. //读取SD卡下的图片   
  90. private InputStream getBitmapInputStreamFromSDCard(String fileName){   
  91. if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {   
  92. String SDCarePath=Environment.getExternalStorageDirectory().toString();   
  93. String filePath=SDCarePath+File.separator+fileName;   
  94. File file=new File(filePath);   
  95. try {   
  96. FileInputStream fileInputStream=new FileInputStream(file);   
  97. return fileInputStream;   
  98. catch (Exception e) {   
  99. e.printStackTrace();   
  100. }   
  101.   
  102. }   
  103. return null;   
  104. }   
  105.   
  106.   
  107. //获取SDCard的目录路径功能   
  108. private String getSDCardPath() {   
  109. String SDCardPath = null;   
  110. // 判断SDCard是否存在   
  111. boolean IsSDcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);   
  112. if (IsSDcardExist) {   
  113. SDCardPath = Environment.getExternalStorageDirectory().toString();   
  114. }   
  115. return SDCardPath;   
  116. }   
  117. //压缩且保存图片到SDCard   
  118. private void compressAndSaveBitmapToSDCard(Bitmap rawBitmap,String fileName,int quality){   
  119. String saveFilePaht=this.getSDCardPath()+File.separator+fileName;   
  120. File saveFile=new File(saveFilePaht);   
  121. if (!saveFile.exists()) {   
  122. try {   
  123. saveFile.createNewFile();   
  124. FileOutputStream fileOutputStream=new FileOutputStream(saveFile);   
  125. if (fileOutputStream!=null) {   
  126. //imageBitmap.compress(format, quality, stream);   
  127. //把位图的压缩信息写入到一个指定的输出流中   
  128. //第一个参数format为压缩的格式   
  129. //第二个参数quality为图像压缩比的值,0-100.0 意味着小尺寸压缩,100意味着高质量压缩   
  130. //第三个参数stream为输出流   
  131. rawBitmap.compress(Bitmap.CompressFormat.JPEG, quality, fileOutputStream);   
  132. }   
  133. fileOutputStream.flush();   
  134. fileOutputStream.close();   
  135. catch (IOException e) {   
  136. e.printStackTrace();   
  137.   
  138. }   
  139. }   
  140. }   
  141.   
  142. //获取图片的缩略图   
  143. private Bitmap getBitmapThumbnail(String filePath){   
  144. BitmapFactory.Options options=new BitmapFactory.Options();   
  145. //true那么将不返回实际的bitmap对象,不给其分配内存空间但是可以得到一些解码边界信息即图片大小等信息   
  146. options.inJustDecodeBounds=true;   
  147. //此时rawBitmap为null   
  148. Bitmap rawBitmap = BitmapFactory.decodeFile(filePath, options);   
  149. if (rawBitmap==null) {   
  150. System.out.println("此时rawBitmap为null");   
  151. }   
  152. //inSampleSize表示缩略图大小为原始图片大小的几分之一,若该值为3   
  153. //则取出的缩略图的宽和高都是原始图片的1/3,图片大小就为原始大小的1/9   
  154. //计算sampleSize   
  155. int sampleSize=computeSampleSize(options, 150200*200);   
  156. //为了读到图片,必须把options.inJustDecodeBounds设回false   
  157. options.inJustDecodeBounds = false;   
  158. options.inSampleSize = sampleSize;   
  159. //原图大小为625x690 90.2kB   
  160. //测试调用computeSampleSize(options, 100, 200*100);   
  161. //得到sampleSize=8   
  162. //得到宽和高位79和87   
  163. //79*8=632 87*8=696   
  164. Bitmap thumbnailBitmap=BitmapFactory.decodeFile(filePath, options);   
  165. //保存到SD卡方便比较   
  166. this.compressAndSaveBitmapToSDCard(thumbnailBitmap, "15.jpg"80);   
  167. return thumbnailBitmap;   
  168. }   
  169.   
  170. //参考资料:   
  171. //http://my.csdn.net/zljk000/code/detail/18212   
  172. //第一个参数:原本Bitmap的options   
  173. //第二个参数:希望生成的缩略图的宽高中的较小的值   
  174. //第三个参数:希望生成的缩量图的总像素   
  175. public static int computeSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {   
  176. int initialSize = computeInitialSampleSize(options, minSideLength,maxNumOfPixels);   
  177. int roundedSize;   
  178. if (initialSize <= 8) {   
  179. roundedSize = 1;   
  180. while (roundedSize < initialSize) {   
  181. roundedSize <<= 1;   
  182. }   
  183. else {   
  184. roundedSize = (initialSize + 7) / 8 * 8;   
  185. }   
  186. return roundedSize;   
  187. }   
  188.   
  189. private static int computeInitialSampleSize(BitmapFactory.Options options,int minSideLength, int maxNumOfPixels) {   
  190. //原始图片的宽   
  191. double w = options.outWidth;   
  192. //原始图片的高   
  193. double h = options.outHeight;   
  194. System.out.println("========== w="+w+",h="+h);   
  195. int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math   
  196. .sqrt(w * h / maxNumOfPixels));   
  197. int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(   
  198. Math.floor(w / minSideLength), Math.floor(h / minSideLength));   
  199. if (upperBound < lowerBound) {   
  200. // return the larger one when there is no overlapping zone.   
  201. return lowerBound;   
  202. }   
  203. if ((maxNumOfPixels == -1) && (minSideLength == -1)) {   
  204. return 1;   
  205. else if (minSideLength == -1) {   
  206. return lowerBound;   
  207. else {   
  208. return upperBound;   
  209. }   
  210. }   
  211.   
  212. /**  
  213. * @param bitmap 需要修改的图片  
  214. * @param pixels 圆角的弧度  
  215. * @return 圆角图片  
  216. */   
  217. //参考资料:   
  218. //http://blog.csdn.net/c8822882/article/details/6906768   
  219. public Bitmap toRoundCorner(Bitmap bitmap, int pixels) {   
  220. Bitmap roundCornerBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);   
  221. Canvas canvas = new Canvas(roundCornerBitmap);   
  222. int color = 0xff424242;//int color = 0xff424242;   
  223. Paint paint = new Paint();   
  224. paint.setColor(color);   
  225. //防止锯齿   
  226. paint.setAntiAlias(true);   
  227. Rect rect = new Rect(00, bitmap.getWidth(), bitmap.getHeight());   
  228. RectF rectF = new RectF(rect);   
  229. float roundPx = pixels;   
  230. //相当于清屏   
  231. canvas.drawARGB(0000);   
  232. //先画了一个带圆角的矩形   
  233. canvas.drawRoundRect(rectF, roundPx, roundPx, paint);   
  234. paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));   
  235. //再把原来的bitmap画到现在的bitmap!!!注意这个理解   
  236. canvas.drawBitmap(bitmap, rect, rect, paint);   
  237. return roundCornerBitmap;   
  238. }   
  239.   
  240. }   

转载地址:https://blog.csdn.net/happy_love1990/article/details/76391516 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android CountDownTimer倒计时器的使用
下一篇:android学习笔记之ImageView的scaleType属性

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2024年03月10日 01时58分18秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章

java 图像渐变_Java基础之在窗口中绘图——渐变填充(GradientApplet 1) 2019-04-21
冒泡排序面向对象java_所谓的面向对象实现的冒泡排序 2019-04-21
proto 客户端 JAVA_Kubernetes官方java客户端之五:proto基本操作 2019-04-21
java编写roguelike_RogueLike地牢生成算法Unity实现 2019-04-21
java ajax 修改数据库数据库数据库_AJAX 自学练习 无刷新提交并修改数据库数据并显... 2019-04-21
java并发编程指南博客_Java并发编程-synchronized指南 2019-04-21
java怎么中断阻塞状态_java并发编程()阻塞方法与中断方法 2019-04-21
java zlib 位运算_位运算入门:找出一个二进制数的最右端的第一个1;计算一个二进制数中1的个数;找出数组中唯一一个出现次数为奇数的数;找出数组中唯二两个出现次数为奇数的数... 2019-04-21
java lua热更新_lua热更新学习 2019-04-21
script执行php文件_php命令行(cli)下执行PHP脚本文件的相对路径的问题解决方法... 2019-04-21
apache 2.4 php5.4_apache2.4+php5.4+my sql 5.6,网站经常无故不能访问 2019-04-21
php apc.dll下载,PHP之APC缓存详细介绍 apc模块安装 2019-04-21
html贝塞尔曲线在线,贝塞尔曲线的一些事情_html/css_WEB-ITnose 2019-04-21
java blockingqueue源码_Java并发队列BlockingQueue实现之ArrayBlockingQueue源码分析 2019-04-21
Java前台显示近20天的东西_第十次课:前台首页设计及显示商品信息 2019-04-21
java开发web网站的路由设计_理解Web路由(浅谈前后端路由与前后端渲染) 2019-04-21
excel如何把顺序倒过来_在excel中怎么使文字颠倒顺序反过来显示呢? 2019-04-21
java 62进制 转换_序列号生成的另一种玩法--62进制如何玩? 2019-04-21
php正则表达式获取图片路径,php 常用正则表达式实例(图片地址,与指定内容获取)... 2019-04-21
脚本语言php是什么意思,PHP脚本语言 2019-04-21