Java&&C# 高质量调整图片尺寸
前言
分享调整图片尺寸保持高分辨率的代码
C#可以使用原生的Image调整,效果很好
Java可以使用原生的IO,也可以使用开源的 Thumbnails 框架
Java
原生IO
/**
* 修改图片尺寸
*
* @param newWidth 新宽度
* @param newHeight 新高度
* @param path 原图片地址
* @param newPath 新图片地址
* @return 修改结果
*/
public static boolean changeSize(int newWidth, int newHeight, String path, String newPath) {
try {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(path));
//字节流转图片对象
Image bi = ImageIO.read(in);
//构建图片流
BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
//绘制改变尺寸后的图
tag.getGraphics().drawImage(bi, 0, 0, newWidth, newHeight, null);
//输出流
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(newPath));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag);
ImageIO.write(tag, "PNG", out);
in.close();
out.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
使用 Thumbnails 框架
github:Thumbnails
这个框架挺好用的,可以旋转图片、调整图片质量(float,范围0.0-1.0)、图片大小等等
官方示例:Examples
maven导入
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
调用
调整图片大小
Thumbnails.of("oldImagePath.jpg")
.size(newWidth, newHeight).outputQuality(1.0F)
.toFile("newImagePath.jpg");
旋转图片 rotate
BufferedImage originalImage = ImageIO.read(new File("original.jpg"));
BufferedImage thumbnail = Thumbnails.of(originalImage)
.size(200, 200)
.rotate(90)
.asBufferedImage();
创建带有水印的缩略图
BufferedImage originalImage = ImageIO.read(new File("original.jpg"));
BufferedImage watermarkImage = ImageIO.read(new File("watermark.png"));
BufferedImage thumbnail = Thumbnails.of(originalImage)
.size(200, 200)
.watermark(Positions.BOTTOM_RIGHT, watermarkImage, 0.5f)
.asBufferedImage();
C#
public static Bitmap ResizeImage(Image image, int width, int height)
{
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
return destImage;
}
调用代码
using (FileStream file = new FileStream(@"oldimg.jpeg", FileMode.Open))
{
Image img = Image.FromStream(file);
Image _img_format = ResizeImage(img, 200, 200);
if (_img_format != null)
{
_img_format.Save(@"newimg.jpeg");
}
}