图片高保真处理

package file;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;

public class ImageUtil {

	/**
	 * 左上方添加图片
	 * @param bgImagePath
	 * @param fgImagePath
	 * @param overlayImagePath
	 */
	public static String overlayLeftTop(String bgImagePath, String fgImagePath,
			String overlayImagePath) {
		return overlay(bgImagePath, fgImagePath, overlayImagePath, 0, 0);
	}
	/**
	 * 右上方添加图片
	 * @param bgImagePath
	 * @param fgImagePath
	 * @param overlayImagePath
	 */
	public static String overlayRightTop(String bgImagePath, String fgImagePath,
			String overlayImagePath) {
		return overlay(bgImagePath, fgImagePath, overlayImagePath, 1, 0);
	}
	/**
	 * 左下方添加图片
	 * @param bgImagePath
	 * @param fgImagePath
	 * @param overlayImagePath
	 */
	public static String overlayLeftButtom(String bgImagePath,
			String fgImagePath, String overlayImagePath) {
		return overlay(bgImagePath, fgImagePath, overlayImagePath, 0, 1);
	}
	/**
	 * 右下方添加图片
	 * @param bgImagePath
	 * @param fgImagePath
	 * @param overlayImagePath
	 */
	public static String overlayRightButtom(String bgImagePath,
			String fgImagePath, String overlayImagePath) {
		return overlay(bgImagePath, fgImagePath, overlayImagePath, 1, 1);
	}

	/**
	 * 合成图片 x:前置图片所在x轴位置 y:前置图片所在y轴位置
	 */
	public static String overlay(String bgImagePath, String fgImagePath,
			String overlayImagePath, int x, int y) {
		if (!strIsValid(bgImagePath) || !strIsValid(fgImagePath)
				|| !strIsValid(overlayImagePath)) {
			throw new IllegalArgumentException();
		}
		BufferedImage bgImage = readImage(bgImagePath);
		BufferedImage fgImage = readImage(fgImagePath);
		// 合成图片
		BufferedImage overlayedImage = overlayImages(bgImage, fgImage, x, y);

		/** 输出图片 */
		if (overlayedImage != null) {
			File file = new File(overlayImagePath);
			if (file.exists())
				file.delete();
			writeImage(overlayedImage, overlayImagePath, "PNG");
		}
		return overlayImagePath;
	}

	/**
	 * 合成图片
	 * 
	 * @param bgImage
	 * @param fgImage
	 * @return
	 */
	public static BufferedImage overlayImages(BufferedImage bgImage,
			BufferedImage fgImage, int x, int y) {
		if (fgImage.getHeight() > bgImage.getHeight()
				|| fgImage.getWidth() > fgImage.getWidth()) {
			return null;
		}

		Graphics2D g = bgImage.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		g.drawImage(bgImage, 0, 0, null);

		g.drawImage(fgImage, x, y, null);

		g.dispose();
		return bgImage;
	}

	/**
	 * 读取图片
	 * 
	 * @param fileLocation
	 * @return
	 */
	public static BufferedImage readImage(String fileLocation) {
		BufferedImage img = null;
		try {
			img = ImageIO.read(new File(fileLocation));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return img;
	}

	/**
	 * 输出图片
	 * 
	 * @param img
	 * @param fileLocation
	 * @param extension
	 */
	public static void writeImage(BufferedImage img, String fileLocation,
			String extension) {
		try {
			BufferedImage bi = img;
			File outputfile = new File(fileLocation);
			ImageIO.write(bi, extension, outputfile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 检查图片的高度和宽度
	 * 
	 * @param imagePath
	 * @param height
	 * @param width
	 * @return
	 */
	public static boolean checkImageHW(String imagePath, int height, int width) {
		if (StrUtil.isNullOrEmpty(imagePath))
			return false;
		try {
			BufferedImage image = ImageIO.read(new File(imagePath));
			int w = image.getWidth();
			int h = image.getHeight();
			return w == width && h == height;
		} catch (IOException e) {
			return false;
		}
	}

	/**
	 * 图片等比例缩小
	 * 
	 * @param fromFileStr
	 *            : 原图片路径
	 * @param saveToFileStr
	 *            : 缩小后图片的路径
	 * @param width
	 *            : 图片缩小后的高度
	 * @param height
	 *            : 图片缩小后的宽度
	 * @throws Exception
	 */
	public static void shrinkImage(String fromFileStr, String saveToFileStr,
			int width, int height)  {
		if (!strIsValid(fromFileStr) || !strIsValid(fromFileStr)) {
			throw new IllegalArgumentException("image path is null");
		}
		try {
			Thumbnails.of(fromFileStr).size(width,height).toFile(saveToFileStr);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 图片缩小
	 * @param source
	 * @param targetW
	 * @param targetH
	 * @param equalProportion 是否等比缩小
	 * @return
	 */
	public static BufferedImage resize(BufferedImage source, int targetW,
			int targetH, boolean equalProportion) {
		int type = source.getType();
		BufferedImage target = null;
		double sx = (double) targetW / source.getWidth();
		double sy = (double) targetH / source.getHeight();
		if (equalProportion) {
			if (sx > sy) {
				sx = sy;
				targetW = (int) (sx * source.getWidth());
			} else {
				sy = sx;
				targetH = (int) (sx * 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;
	}

	public static boolean strIsValid(String str) {
		return str != null && !str.trim().equals("");
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenCV是一个开源的计算机视觉库,它提供了丰富的图像处理和计算机视觉功能。虽然OpenCV主要用于图像处理和计算机视觉任务,但它并不直接提供图像压缩的功能。然而,您可以使用OpenCV与其他压缩算法和库结合使用来实现保真压缩图片的目标。 常见的图像压缩算法包括JPEG和PNG。JPEG是一种有损压缩算法,可以在一定程度上减小图像文件的大小,但可能会引入一些可见的失真。PNG是一种无损压缩算法,可以保持图像的完整性,但文件大小通常较大。 您可以使用OpenCV加载和处理图像,然后使用其他库或工具来进行图像压缩。例如,您可以使用Python中的PIL(Python Imaging Library)库来保存JPEG或PNG格式的图像,并选择适当的压缩参数来平衡文件大小和图像质量之间的关系。 下面是一个示例代码片段,演示了如何使用OpenCV和PIL库来进行JPEG和PNG格式的图像压缩: ```python import cv2 from PIL import Image # 读取图像 image = cv2.imread('input_image.jpg') # 进行图像处理 # ... # 保存为JPEG格式 cv2.imwrite('compressed_image.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 90]) # 使用PIL库保存为PNG格式 pil_image = Image.fromarray(image) pil_image.save('compressed_image.png', optimize=True) ``` 在上述示例中,`cv2.imwrite`函数用于保存JPEG格式的图像,并通过`cv2.IMWRITE_JPEG_QUALITY`参数指定了压缩质量(范围为0-100)。较高的质量值会导致较小的压缩率和较大的文件大小。 对于PNG格式的图像,我们使用了PIL库的`Image.fromarray`函数将OpenCV图像对象转换为PIL图像对象,然后使用`save`方法保存为PNG格式。`optimize=True`参数会启用额外的压缩优化。 请注意,实际的压缩效果和文件大小会受到图像内容、压缩参数的选择以及使用的压缩库的影响。因此,您可以根据具体需求进行调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值