在我们经常应用开发中,经常用到将drawable和string相互转化。注意这情况最好用于小图片入icon等。
public synchronized Drawable byteToDrawable(String icon) { byte[] img=Base64.decode(icon.getBytes(), Base64.DEFAULT); Bitmap bitmap; if (img != null) { bitmap = BitmapFactory.decodeByteArray(img,0, img.length); @SuppressWarnings("deprecation") Drawable drawable = new BitmapDrawable(bitmap); return drawable; } return null; } public synchronized String drawableToByte(Drawable drawable) { if (drawable != null) { 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); int size = bitmap.getWidth() * bitmap.getHeight() * 4; // 创建一个字节数组输出流,流的大小为size ByteArrayOutputStream baos = new ByteArrayOutputStream(size); // 设置位图的压缩格式,质量为100%,并放入字节数组输出流中 bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // 将字节数组输出流转化为字节数组byte[] byte[] imagedata = baos.toByteArray(); String icon= Base64.encodeToString(imagedata, Base64.DEFAULT); return icon; } return null; }
版权声明:本文为博主原创文章,未经博主允许不得转载。