码迷,mamicode.com
首页 > 编程语言 > 详细

将byte[]数组数据转换为图片用于预览显示

时间:2016-01-09 21:35:36      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:

假如服务器返回给你的图片信息是byte[] 然后你需要将起转换成图片显示到你的view中去:

按以下的步骤

1.将获取的byte数组保存 假如为temp[];

2.将temp[]转化为bitmap,你可以使用下面的这个方法 :

/**
* 将字节数组转换为ImageView可调用的Bitmap对象
* @param bytes
* @param opts 转换属性设置
* @return
**/

public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {



	     if (bytes != null)

	        if (opts != null) 
	             return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts); 
	        else

	            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 
	     return null;

	}

  

  

 

  其中的这个Options是BitmapFactory.Options 大致功能就是设置你转换成bitmap的属性(大小 宽 高 编码格式 预览 等),为了防止图片过大导致oom我们可以获取预览就可以了:

  

BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2;

 3.这样你把这个opts传入上面的函数中,我们获取的bitmap 就是原图的1/4大小了。如果你还需要缩放成固定的宽高来使用 下面提供一个缩放方法:

/** 
     * @param 图片缩放 
     * @param bitmap 对象 
     * @param w 要缩放的宽度 
     * @param h 要缩放的高度 
     * @return newBmp 新 Bitmap对象 
     */  	

public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h){  
        int width = bitmap.getWidth();  
        int height = bitmap.getHeight();  
        Matrix matrix = new Matrix();  
        float scaleWidth = ((float) w / width);  
        float scaleHeight = ((float) h / height);  
        matrix.postScale(scaleWidth, scaleHeight);  
        Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,  
                matrix, true);  
        return newBmp;  
    }  

  这样就能获取到你想要的高度和宽度的图片 是不是很方便呢

 

将byte[]数组数据转换为图片用于预览显示

标签:

原文地址:http://www.cnblogs.com/yjpjy/p/5117219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!