美文网首页
BitMap、Drawable、InputStream、Byte

BitMap、Drawable、InputStream、Byte

作者: 技术客栈 | 来源:发表于2020-09-01 19:10 被阅读0次

该方法主要是Bitmap、Drawable、InputStream、Byte[]之间的互相转换.

/**
     * Bitmap 转换为 InputStream
     * @param bitmap
     * @return
     */
    public InputStream bitmapToInputStream(Bitmap bitmap){
        InputStream is;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        is = new ByteArrayInputStream(baos .toByteArray());
        return is;
    }
    
    
    /**
     * Bitmap 转换为 byte[]
     * @param is
     * @return
     */
    public byte[] bitmapToByteArray(InputStream is){
        byte[] data;
        Bitmap defaultIcon = BitmapFactory.decodeStream(is);
          ByteArrayOutputStream stream = new ByteArrayOutputStream();
          defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);
          data = stream.toByteArray();
          return data;
    }
    
    /**
     * Drawable 转换为 byte[]
     * @param defaultIcon
     * @return
     */
    public byte[] drawableToByteArray(Bitmap defaultIcon){
          byte[] data;
          Drawable d = null; // the drawable (Captain Obvious, to the rescue!!!)
          Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
          ByteArrayOutputStream stream = new ByteArrayOutputStream();
          defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);
          data = stream.toByteArray();
          return data;
    }  
    
    /**
     * byte 转换为 Bitmap
     * @param bitmapdata
     * @return
     */
    
    public Bitmap byteArrayToBitmap(byte[] bitmapdata){
        Bitmap bitmap =BitmapFactory.decodeByteArray(bitmapdata, 0,bitmapdata.length);
        return bitmap;
    }
    
    
    

相关文章

网友评论

      本文标题:BitMap、Drawable、InputStream、Byte

      本文链接:https://www.haomeiwen.com/subject/txxbsktx.html