1、Drawable --> Bitmap
- Bitmap drawable2Bitmap(Drawable drawable) {
- if (drawable instanceof BitmapDrawable) {
- return ((BitmapDrawable) drawable).getBitmap();
- } else if (drawable instanceof NinePatchDrawable) {
- Bitmap bitmap = Bitmap
- .createBitmap(
- drawable.getIntrinsicWidth(),
- drawable.getIntrinsicHeight(),
- drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
- : Bitmap.Config.RGB_565);
- Canvas canvas = new Canvas(bitmap);
- drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
- drawable.getIntrinsicHeight());
- drawable.draw(canvas);
- return bitmap;
- } else {
- return null;
- }
- }
2、从资源中获取的Drawable --> Bitmap
- Resources res = getResources();
- Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.pic);
3、Bitmap --> Drawable
- Drawable bitmap2Drawable(Bitmap bitmap) {
- return new BitmapDrawable(bitmap);
- }
4、Bitmap --> byte[]
- byte[] Bitmap2Bytes(Bitmap bm) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
- return baos.toByteArray();
- }
5、 byte[] --> Bitmap
- Bitmap Bytes2Bimap(byte[] b) {
- if (b.length != 0) {
- return BitmapFactory.decodeByteArray(b, 0, b.length);
- } else {
- return null;
- }
- }
-
-
-
- /**
- * 得到本地或者网络上的bitmap url - 网络或者本地图片的绝对路径,比如:
- *
- * A.网络路径: url="http://blog.foreverlove.us/girl2.png" ;
- *
- * B.本地路径:url="file://mnt/sdcard/photo/image.png";
- *
- * C.支持的图片格式 ,png, jpg,bmp,gif等等
- *
- * @param url
- * @return
- */
- public static Bitmap GetLocalOrNetBitmap(String url)
- {
- Bitmap bitmap = null;
- InputStream in = null;
- BufferedOutputStream out = null;
- try
- {
- in = new BufferedInputStream(new URL(url).openStream(), Constant.IO_BUFFER_SIZE);
- final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
- out = new BufferedOutputStream(dataStream, Constant.IO_BUFFER_SIZE);
- copy(in, out);
- out.flush();
- byte[] data = dataStream.toByteArray();
- bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
- data = null;
- return bitmap;
- }
- catch (IOException e)
- {
- e.printStackTrace();
- return null;
- }
- }
- 说明:Constant.IO_BUFFER_SIZE 是一个常量而已,可以改成常数,比如2*1024,其实取决于你的图片大小,自己根据图片的大小自己设定吧。。。。
附加的copy函数
private static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}