Bitmap,byte[],Drawable,InputStream相互转化工具类

本文详细介绍如何在不同数据类型间进行转换,包括byte数组与输入流、位图与字节数组之间的相互转换等核心操作。文章还介绍了Bitmap、Drawable、InputStream间的转换方法,并提供了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、将byte[]转换成InputStream  

    byte[] b;

        ByteArrayInputStream bais = new ByteArrayInputStream(b);  
       
  

2、 将InputStream转换成byte[]  

    (1)

InputStream inStream;

    ByteArrayOutputStream swapStream = new ByteArrayOutputStream();

    byte[] buff = new byte[100];

    int rc = 0;

    try {

  while ((rc = inStream.read(buff, 0, 100)) > 0) {

  swapStream.write(buff, 0, rc);

  }

  } catch (IOException e) {

  e.printStackTrace();

  }

    byte[] in2b = swapStream.toByteArray();

(2)

    InputStream is;

        String str = ""; 

        byte[] readByte = new byte[1024];  

        int readCount = -1;  

        try {  

            while ((readCount = is.read(readByte, 0, 1024)) != -1) {  

                str += new String(readByte).trim();  

         } catch (Exception e) {  

            e.printStackTrace();  

}  

byte[] in2b = str.getBytes();

  

3、 Bitmap转换成byte[]  

Bitmap bm; 

    ByteArrayOutputStream baos = new ByteArrayOutputStream();  

    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);  

    byte[] b = baos.toByteArray();   

  

4、 byte[]转换成Bitmap  

    byte[] b;

    if (b.length != 0) 

      Bitmap bm = BitmapFactory.decodeByteArray(b, 0, b.length);  

  

5、Drawable转换成Bitmap 

    Drawable drawable; 

    Bitmap bitmap = Bitmap  

            .createBitmap(  

                drawable.getIntrinsicWidth(),  

                drawable.getIntrinsicHeight(),  

                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888  

                     : Bitmap.Config.RGB_565); 

  

6、 Bitmap转换成Drawable  

    Bitmap bitmap;

    BitmapDrawable bd = new BitmapDrawable(bitmap);  

    Drawable d = (Drawable) bd;  


7、 将Bitmap转换成InputStream  

    Bitmap bm;

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

    InputStream is = new ByteArrayInputStream(baos.toByteArray());  

  

8、 将InputStream转换成Bitmap  

    InputStream is;

    Bitmap bm = BitmapFactory.decodeStream(is); 

  

9、 Drawable转换成InputStream  

    Drawable d;

    //先把drawable转换成Bitmap 

    //再把Bitmap 转换成 InputStream    

  

10、 InputStream转换成Drawable  

    InputStream is;

    //先把InputStream 转换成 Bitmap 

    //再把Bitmap 转换成 Drawable  


11、 Drawable转换成byte[] 

    Drawable d;

    //先把Drawable 转换成 Bitmap 

    //再把Bitmap 转换成 byte[]

 

12、 byte[]转换成Drawable  

    byte[] b; 

    //先把byte[] 转换成 Bitmap 

    //再把Bitmap 转换成 Drawable  

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值