本地文件转 Drawable

/**
 * 将本地文件转换为 Drawable
*/
private Drawable iconDrawable(String file)
{
    if (file == null || file.isEmpty())
    {
        return null;
    }

	Drawable drawable = null;
	try
	{
		FileInputStream fis = new FileInputStream(file);
		Bitmap bitmap  = BitmapFactory.decodeStream(fis);
		drawable = new BitmapDrawable(getResources(), bitmap);
	}
	catch (FileNotFoundException e)
	{
		e.printStackTrace();
	}

	return drawable;
}

或者直接利用:Bitmap bitmap  = BitmapFactory.decodeFile(file); 获取 Bitmap,再构造出 Drawable。

说到 Bitmap,顺便讲一下Bitmap 改变图片尺寸的方法:

下面例子是从 assets 目录下读取图片文件,并支持改变图片尺寸返回 Bitmap

/**
 * 将 assets 下的图片转换为 Bitmap
 * @param fileName	-- assets 下图片文件
 * @param dst_w		-- 输出宽度(为 0 时原图尺寸输出)
 * @param dst_h		-- 输出高度(为 0 时原图尺寸输出)
 * @return Bitmap 图片
 * 说明:
 *		dst_w / dst_h 任意一值为 0 时,原图尺寸输出
 */
private Bitmap imageFromAssetFile(String fileName, int dst_w, int dst_h)
{
	Bitmap image = null;
	try
	{
		AssetManager am = getResources().getAssets();
		InputStream is = am.open(fileName);
		if (is != null)
		{
			image = BitmapFactory.decodeStream(is);
			is.close();
		}
	}
	catch (Exception e)
	{
	}

	if (dst_w == 0 || dst_h == 0)
	{
		return image;
	}

	if (image == null)
    {
		return null;
	}
		
	// 调整图片大小
	int src_w = image.getWidth();
	int src_h = image.getHeight();
	float scale_w = ((float)dst_w) / src_w;
	float scale_h = ((float)dst_h) / src_h;
	Matrix matrix = new Matrix();
	matrix.postScale(scale_w, scale_h);

	return Bitmap.createBitmap(image, 0, 0, src_w, src_h, matrix, true);
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值