欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

图片缩放

程序员文章站 2022-03-16 15:16:08
...
/**
	 * 通过传进来的二进制图片流,将图片缩放后返回,用于文件上传取得缩放图,然后存数据库
	 * 
	 * @param bt
	 *            原图二进制
	 * @param targetW
	 *            目标宽度
	 * @param targetH
	 *            目标长度
	 * @return 缩放后图片的二进制
	 * @throws IOException
	 *             流读写异常
	 */
	public static byte[] resize(byte[] bt, Integer targetW, Integer targetH)
			throws IOException {
		ByteArrayInputStream bai = new java.io.ByteArrayInputStream(bt);
		BufferedImage bimg = javax.imageio.ImageIO.read(bai);
		BufferedImage target = resize(bimg, targetW, targetH);
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
		encoder.encode(target);
		byte[] arr = os.toByteArray();
		os.flush();
		os.close();
		bai.close();
		return arr;
	}

 昨天做的一个图片缩放,能够将上传的文件进行缩放后返回字节数组,然后存放数据库或其它操作。

 

public static BufferedImage resize(BufferedImage source, int targetW,
			int targetH) throws IOException {
		// targetW,targetH分别表示目标长和宽
		int type = source.getType();
		BufferedImage target = null;
		double sx = (double) targetW / source.getWidth();
		double sy = (double) targetH / source.getHeight();
		// 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放
		// 则将下面的if else语句注释即可
		if (sx > sy) {
			sx = sy;
			targetW = (int) (sx * source.getWidth());
		} else {
			sy = sx;
			targetH = (int) (sy * source.getHeight());
		}
		if (type == BufferedImage.TYPE_CUSTOM) {
			ColorModel cm = source.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(targetW,
					targetH);
			boolean alphaPremultiplied = cm.isAlphaPremultiplied();
			target = new BufferedImage(cm, raster, alphaPremultiplied, null);
		} else
			target = new BufferedImage(targetW, targetH, type);
		Graphics2D g = target.createGraphics();

		g.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_QUALITY);
		g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
		g.dispose();
		return target;
	}

 

相关标签: OS