在Android SDK中说明可以支持的图片格式如下:png , jpg , gif,和bmp。

1.Bitmap的创建

借助于BitmapFactory。
1)资源中的图片
使用BitmapFactory获取位图
Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.testImg);
或者是
Resources res=getResources();
//使用BitmapDrawable获取位图
//使用BitmapDrawable (InputStream is)构造一个BitmapDrawable;
//使用BitmapDrawable类的getBitmap()获取得到位图;
// 读取InputStream并得到位图
InputStream is=res.openRawResource(R.drawable.testImg);
BitmapDrawable bmpDraw=new BitmapDrawable(is);
Bitmap bmp=bmpDraw.getBitmap();

2)SD卡中的图片
Bitmap bmp = BitmapFactory.decodeFile("/sdcard/testBitmap/testImg.png")

2. 把 Bitmap 保存在sdcard中
File fImage = new File("/sdcard/testBitmap/testImg.png");
fImage.createNewFile();
FileOutputStream iStream = new FileOutputStream(fImage);
bmp.compress(CompressFormat.PNG, 100, iStream);
iStream.close();
fImage.close();
iStream =null;
fImage =null;
//写到输出流里,就保存到文件了。

3.使用网络中的图片

//图片的链接地址
String imgURLStr = "http://tx.bdimg.com/sys/portrait/item/990e6271796a7a6c170c.jpg";
URL imgURL = new URL(imgURLStr);
URLConnection conn = imgURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);


//下载图片
Bitmap bmp = BitmapFactory.decodeStream(bis);

//关闭Stream
bis.close();
is.close();
imgURL =null;

4.显示图片
1)转换为BitmapDrawable对象显示位图
// 转换为BitmapDrawable对象
BitmapDrawable bmpDraw=new BitmapDrawable(bmp);
// 显示位图
ImageView iv2 = (ImageView)findViewById(R.id.ImageView02);
iv2.setImageDrawable(bmpDraw);
2)使用Canvas类显示位图
canvas.drawBitmap(bmp, 0, 0, null);

5.缩放位图
1)将一个位图按照需求重画一遍,画后的位图就是我们需要的了,与位图的显示几乎一样:drawBitmap(Bitmap bitmap, Rect src, Rect

dst, Paint paint)。

2)在原有位图的基础上,缩放原位图,创建一个新的位图:CreateBitmap(Bitmap source, int x, int y, int width, int height,

Matrix m, boolean filter)

3)借助Canvas的scale(float sx, float sy) ,不过要注意此时整个画布都缩放了。

4)借助Matrix:

Matrix matrix=new Matrix();
matrix.postScale(0.2f, 0.2f);
Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(),bmp.getHeight(),matrix,true);
canvas.drawBitmap(dstbmp, 10, 10, null);
6.旋转位图
借助Matrix或者Canvas来实现。

Matrix matrix=new Matrix();
matrix.postRotate(45);
Bitmap dstbmp=Bitmap.createBitmap(bmp,0,0,bmp.getWidth(), bmp.getHeight(),matrix,true);
canvas.drawBitmap(dstbmp, 10, 10, null);

<!--EndFragment-->

更多相关文章

  1. Android Fresco图片处理库用法API英文原文文档2-1(Facebook开源An
  2. Android 图片阴影处理分析!
  3. LinearLayout按下(pressed)或获取焦点(focused)时背景设置不同颜
  4. android之网络请求 -- 获取RecyclerView的列表项(图片 + 文字)
  5. Android系列之Post图片和数据
  6. Android 自定义camera压缩图片到指定大小
  7. Android matrix偏移(平移),旋转,缩放,倾斜的原理
  8. iphone/android比较学习之──图片、文件、字符串

随机推荐

  1. Cocos2d-x Mac下环境搭建
  2. Android(安卓)ionic工程中调用webrtc获取
  3. Android沉浸式状态栏设计的实例代码
  4. Android(安卓)音视频开发(五) -- 使用 Me
  5. Binder通信机制
  6. android-实现黑名单拦截
  7. GreenDao 问题集合
  8. 游戏开发学习路线规划(整理自网络)
  9. android Dialog去掉黑色的背景和边框
  10. showDividers属性和showAsAction属性