android上的图片缩放处理

本文介绍了一种在Android平台上实现图片压缩与缩放的方法。通过使用Java代码,该方法可以将图片调整到指定的宽度和高度,并进行压缩以节省存储空间。文中详细解释了如何读取图片、创建矩阵进行缩放以及如何将压缩后的图片转换为字节数组。

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

android上的图片缩放处理



import java.io.ByteArrayOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.util.Log;

public class PhotoCompressUtils {
	/**
	 * 缩放图片,返回一个byte
	 * 
	 * @param filePath
	 *            文件路径
	 * @param width
	 *            宽度
	 * @param height
	 *            高度
	 * @return 一个图片数组
	 * @throws Exception
	 */
	public static byte[] compress(String filePath, int width, int height)
			throws Exception {

		Bitmap bm = CreatImage(filePath);
		if (bm.getWidth() < width || bm.getHeight() < height) {
			Log.e("Image", "file size not have the format!!");
			return null;
		}
		bm = zoomImage(bm, 200, 200);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, out);
		out.flush();
		out.close();
		return out.toByteArray();

	}

	/**
	 * 图片处理
	 * 
	 * @param bgimage
	 * @param newWidth
	 * @param newHeight
	 * @return
	 */
	public static Bitmap zoomImage(Bitmap bgimage, int newWidth, int newHeight) {
		// 获取这个图片的宽和高
		int width = bgimage.getWidth();
		int height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算缩放率,新尺寸除原始尺寸
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, width, height,
				matrix, true);
		return bitmap;
	}

	/*
	 * 获得图片
	 */
	public final static Bitmap CreatImage(String pathName) {
		Bitmap bitmaptemp = null;
		bitmaptemp = BitmapFactory.decodeFile(pathName);
		return bitmaptemp;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值