android 中的 Bitmap 相关
1.Bitmap转Drawable
//xxx根据你的情况获取
Bitmap bitmap=xxx;
//BitmapDrawable bitmapDrawable=BitmapDrawable(bitmap);(被弃用,原因是:不能确定drawable已经设置了正确的目标屏幕)
BitmapDrawable bitmapDrawable= new BitmapDrawable(this.getResources(),bitmap);
因为BtimapDrawable是Drawable的子类,最终直接使用bitmapDrawable对象即可。
2.Drawable转Bitmap
Drawable drawable=xxx; //xxx根据自己的情况获取drawable
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap= bitmapDrawable .getBitmap();
最终bitmap就是我们需要的Bitmap对象了。
3.Bitmap的加载
Bitmap比较特别 因为其不可创建 而只能借助于BitmapFactory 而根据图像来源又可分以下几种情况:
位图是我们开发中最常用的资源,毕竟一个漂亮的界面对用户是最有吸引力的。
3.1 从资源中获取位图
png图片 如:R.drawable.tianjin,代码如下:
Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.tianjin); // 加载资源图片
图像文件 如: /sdcard/dcim/tianjin.jpeg,代码如下:
3.2 从SD卡中获取位图
Bitmap bmp = BitmapFactory.decodeFile("/sdcard/dcoim/tianjin.jpeg") //加载文件图片
3.3 读取InputStream并得到位图
InputStream is=res.openRawResource(R.drawable.pic180);
BitmapDrawable bitmapDrawable=new BitmapDrawable(is);
Bitmap bitmap=bitmapDrawable.getBitmap();
以上方法在编程的时候可以自由选择,在Android SDK中说明可以支持的图片格式如下:png (preferred), jpg (acceptable), gif (discouraged),和bmp(Android SDK Support Media Format)。
4. 获取位图的信息
要获取位图信息,比如位图大小、像素、density、透明度、颜色格式等,获取得到Bitmap就迎刃而解了,这些信息在Bitmap的手册中,这里只是辅助说明以下2点:
4.1在Bitmap中对RGB颜色格式使用Bitmap.Config定义,仅包括ALPHA_8、ARGB_4444、ARGB_8888、RGB_565,缺少了一些其他的,比如说RGB_555,在开发中可能需要注意这个小问题;
4.2Bitmap还提供了compress()接口来压缩图片,不过AndroidSAK只支持PNG、JPG格式的压缩;其他格式的需要Android开发人员自己补充了。
5. 显示位图
显示位图可以使用核心类Canvas,通过Canvas类的drawBirmap()显示位图,或者借助于BitmapDrawable来将Bitmap绘制到Canvas。当然,也可以通过BitmapDrawable将位图显示到View中。
转换为BitmapDrawable对象显示位图
// 获取位图
Bitmap bitmap=BitmapFactory.decodeResource(this.getResources(), R.drawable.pic180);
// 转换为BitmapDrawable对象
BitmapDrawable bitmapDrawable=new BitmapDrawable(bitmap);
// 显示位图
ImageView iv= (ImageView)findViewById(R.id.iv);
iv.setImageDrawable(bitmapDrawable);
使用Canvas类显示位图
这儿采用一个继承自View的子类Panel,在子类的OnDraw中显示
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new Panel(this));
}
class Panel extends View {
public Panel(Context context) {
super(context);
}
public void onDraw(Canvas canvas) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.pic180);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(bitmap, 10, 10, null);
}
}
}
6. Bitmap 相关应用
- 本地保存 即 把 Bitmap 保存在sdcard中
可以保存为几种格式:png,gif等貌似都可以,自己写的:
public void saveBitmap(Bitmap bitmap, String bitmapName) {
//创建目标文件夹及文件
File fileImage = new File("/sdcard/Note/" + bitmapName + ".png");
if (!fileImage.getParentFile().exists()) {
System.out.println(fileImage.getParentFile());
fileImage.getParentFile().mkdirs();
}
try {
fileImage.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
/*
* 参照Bitmap 的API方法 compress(Bitmap.CompressFormat format, int quality,
* OutputStream stream) Write a compressed version of the bitmap to the
* specified outputstream. 写到输出流里,就保存到文件了。
*/
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
- 得到网路图片
Java代码
//图片的链接地址
String imageURI = "http://202.140.96.134:8080/FS-RSS/img/RN.png";
try {
URL imageURL = new URL(imageURI );
URLConnection conn =imageURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
is.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
7. 位图缩放
(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) (Preconcat the current matrix with the specified scale.),不过要注意此时整个画布都缩放了。
(4)借助Matrix:
Bitmap bitmap= BitmapFactory.decodeResource(this.getResources(), R.drawable.pic180);
Matrix matrix=new Matrix();
matrix.postScale(0.2f, 0.2f);
Bitmap dstbmp=Bitmap.createBitmap(bitmap,0,0,bmp.getWidth(),
bmp.getHeight(),matrix,true);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(dstbmp, 10, 10, null);
8. 位图旋转
同样,位图的旋转也可以借助Matrix或者Canvas来实现。
Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.pic180);
Matrix matrix=new Matrix();
matrix.postScale(0.8f, 0.8f);//缩放
matrix.postRotate(45);//旋转
Bitmap destinationBitmap=Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);
canvas.drawColor(Color.BLACK);
canvas.drawBitmap(destinationBitmap, 10, 10, null);
9.图片水印的生成方法
生成水印的过程。其实分为三个环节:第一,载入原始图片;第二,载入水印图片;第三,保存新的图片。
private Bitmap createBitmap(Bitmap source, Bitmap watermark) {
String tag = "createBitmap";
Log.d(tag, "create a new bitmap");
if (source == null) {
return null;
}
int w = source.getWidth();
int h = source.getHeight();
int ww = watermark.getWidth();
int wh = watermark.getHeight();
// create the new blank bitmap
Bitmap newBitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);// 创建一个新的和SRC长度宽度一样的位图
Canvas canvas = new Canvas(newBitmap);
// draw src into
canvas.drawBitmap(source, 0, 0, null);// 在 0,0坐标开始画入src
// draw watermark into
canvas.drawBitmap(watermark, w - ww + 5, h - wh + 5, null);// 在src的右下角画入水印
// save all clip
canvas.save(Canvas.ALL_SAVE_FLAG);// 保存
// store
canvas.restore();// 存储
return newBitmap;
}
10.Canvas的save和restore
onDraw方法会传入一个Canvas对象,它是你用来绘制控件视觉界面的画布。
在onDraw方法里,我们经常会看到调用save和restore方法,它们到底是干什么用的呢?
save:用来保存Canvas的状态。save之后,可以调用Canvas的平移、放缩、旋转、错切、裁剪等操作。
restore:用来恢复Canvas之前保存的状态。防止save后对Canvas执行的操作对后续的绘制有影响。
save和restore要配对使用(restore可以比save少,但不能多),如果restore调用次数比save多,会引发Error。save和restore之间,往往夹杂的是对Canvas的特殊操作。
例如:我们先想在画布上绘制一个右向的三角箭头,当然,我们可以直接绘制,另外,我们也可以先把画布旋转90°,画一个向上的箭头,然后再旋转回来(这种旋转操作对于画圆周上的标记非常有用)。然后,我们想在右下角有个20像素的圆,那么,onDraw中的核心代码是:
int px = getMeasuredWidth();
int py = getMeasuredWidth();
// Draw background
canvas.drawRect(0, 0, px, py, backgroundPaint);
canvas.save();
canvas.rotate(90, px/2, py/2);
// Draw up arrow
canvas.drawLine(px / 2, 0, 0, py / 2, linePaint);
canvas.drawLine(px / 2, 0, px, py / 2, linePaint);
canvas.drawLine(px / 2, 0, px / 2, py, linePaint);
canvas.restore();
// Draw circle
canvas.drawCircle(px - 10, py - 10, 10, linePaint);
从这两个图中,我们就能看到圆圈位置的明显差异。不进行Canvas的save和restore操作的话,所有的图像都是在画布旋转90°后的画布上绘制的。当执行完onDraw方法,系统自动将画布恢复回来。save和restore操作执行的时机不同,就能造成绘制的图形不同。