android中Bitmap用法(显示,保存,缩放,旋转)实例分析
本文实例讲述了android中Bitmap用法。分享给大家供大家参考。具体如下:
在AndroidSDK中可以支持的图片格式如下:png,jpg,gif和bmp。
1.Bitmap的创建
借助于BitmapFactory。
1)资源中的图片
使用BitmapFactory获取位图
Bitmapbmp=BitmapFactory.decodeResource(this.getResources(),R.drawable.testImg);
或者是:
Resourcesres=getResources(); //使用BitmapDrawable获取位图 //使用BitmapDrawable(InputStreamis)构造一个BitmapDrawable; //使用BitmapDrawable类的getBitmap()获取得到位图; //读取InputStream并得到位图 InputStreamis=res.openRawResource(R.drawable.testImg); BitmapDrawablebmpDraw=newBitmapDrawable(is); Bitmapbmp=bmpDraw.getBitmap();
2)SD卡中的图片
Bitmapbmp=BitmapFactory.decodeFile("/sdcard/testBitmap/testImg.png")
2.把Bitmap保存在sdcard中
FilefImage=newFile("/sdcard/testBitmap/testImg.png"); fImage.createNewFile(); FileOutputStreamiStream=newFileOutputStream(fImage); bmp.compress(CompressFormat.PNG,100,iStream); iStream.close(); fImage.close(); iStream=null; fImage=null; //写到输出流里,就保存到文件了。
3.使用网络中的图片
//图片的链接地址 StringimgURLStr="http://tx.bdimg.com/sys/portrait/item/990e6271796a7a6c170c.jpg"; URLimgURL=newURL(imgURLStr); URLConnectionconn=imgURL.openConnection(); conn.connect(); InputStreamis=conn.getInputStream(); BufferedInputStreambis=newBufferedInputStream(is); //下载图片 Bitmapbmp=BitmapFactory.decodeStream(bis); //关闭Stream bis.close(); is.close(); imgURL=null;
4.显示图片
1)转换为BitmapDrawable对象显示位图
//转换为BitmapDrawable对象 BitmapDrawablebmpDraw=newBitmapDrawable(bmp); //显示位图 ImageViewiv2=(ImageView)findViewById(R.id.ImageView02); iv2.setImageDrawable(bmpDraw);
2)使用Canvas类显示位图
canvas.drawBitmap(bmp,0,0,null);
5.缩放位图
1)将一个位图按照需求重画一遍,画后的位图就是我们需要的了,与位图的显示几乎一样:
drawBitmap(Bitmapbitmap,Rectsrc,Rectdst,Paintpaint)
2)在原有位图的基础上,缩放原位图,创建一个新的位图:
CreateBitmap(Bitmapsource,intx,inty,intwidth,intheight,Matrixm,booleanfilter)
3)借助Canvas的scale(floatsx,floatsy),不过要注意此时整个画布都缩放了。
4)借助Matrix:
Matrixmatrix=newMatrix(); matrix.postScale(0.2f,0.2f); Bitmapdstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true); canvas.drawBitmap(dstbmp,10,10,null);
6.旋转位图
借助Matrix或者Canvas来实现。
Matrixmatrix=newMatrix(); matrix.postRotate(45); Bitmapdstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true); canvas.drawBitmap(dstbmp,10,10,null);
希望本文所述对大家的Android程序设计有所帮助。