use*_*187 41 java bufferedimage
我正在尝试调整缓冲图像的大小.我能够存储它并显示在一个jframe没有问题,但我似乎无法调整大小.有关如何更改此功能以使其工作并将图像显示为200*200文件的任何提示都会很棒
private void profPic(){
String path = factory.getString("bottle");
BufferedImage img = ImageIO.read(new File(path));
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
Graphics2D g = dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
g.dispose();
return dimg;
}
Run Code Online (Sandbox Code Playgroud)
Ocr*_*oke 51
更新的答案
我不记得为什么我原来的答复工作,但在一个单独的环境已经测试了它,我同意,原来接受的答案不工作(为什么我说这没有我不记得其一).另一方面,这确实有效:
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = dimg.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
return dimg;
}
Run Code Online (Sandbox Code Playgroud)
coo*_*ird 19
如果所需要的所有是一个调整BufferedImage的resize方法,那么Thumbnailator库可以做到这一点很容易:
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
return Thumbnails.of(img).size(newW, newH).asBufferedImage();
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将调整大小img以适应维度newW和newH原始图像的宽高比.
如果不需要保持纵横比并且需要精确调整到给定尺寸,则forceSize可以使用该size方法代替方法:
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
return Thumbnails.of(img).forceSize(newW, newH).asBufferedImage();
}
Run Code Online (Sandbox Code Playgroud)
使用该Image.getScaledInstance方法不能保证对于调整大小的图像将保持原始图像的宽高比,此外,它通常非常慢.
Thumbnailator使用一种技术来逐步调整图像的大小,这种技术可以比Image.getScaledInstance实现通常具有可比性的图像质量快几倍.
免责声明:我是这个库的维护者.
小智 5
这是我用来调整缓冲图像大小的一些代码,没有多余的装饰,非常快:
public static BufferedImage scale(BufferedImage src, int w, int h)
{
BufferedImage img =
new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
int x, y;
int ww = src.getWidth();
int hh = src.getHeight();
int[] ys = new int[h];
for (y = 0; y < h; y++)
ys[y] = y * hh / h;
for (x = 0; x < w; x++) {
int newX = x * ww / w;
for (y = 0; y < h; y++) {
int col = src.getRGB(newX, ys[y]);
img.setRGB(x, y, col);
}
}
return img;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
86389 次 |
| 最近记录: |