BitMap、Drawable、InputStream、Byte[]互换

该方法主要是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;
    }
    
    
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。