Java 按比例缩小图片应该怎么实现?
答案:2 悬赏:80
解决时间 2021-02-27 21:13
- 提问者网友:夕夏残阳落幕
- 2021-02-26 23:15
Java 按比例缩小图片应该怎么实现?
最佳答案
- 二级知识专家网友:陪伴是最长情的告白
- 2021-02-27 00:37
public Image resizeImg(Image img, int newWidth, int newHeight) {
int imgW = img.getWidth();
int imgH = img.getHeight();
int[] srcPixels = new int[imgW * imgH];
int[] destPixels = new int[newWidth * newHeight];
img.getRGB(srcPixels, 0, imgW, 0, 0, imgW, imgH);
int srcX;
int srcY;
for (int y = 0; y < newHeight; ++y) {
for (int x = 0; x < newWidth; ++x) {
srcX = (x * imgW) / newWidth;
srcY = (y * imgH) / newHeight;
destPixels[x + y * newWidth] = srcPixels[srcX + srcY * imgW];
}
}
return Image.createRGBImage(destPixels, newWidth, newHeight, true);
}
int imgW = img.getWidth();
int imgH = img.getHeight();
int[] srcPixels = new int[imgW * imgH];
int[] destPixels = new int[newWidth * newHeight];
img.getRGB(srcPixels, 0, imgW, 0, 0, imgW, imgH);
int srcX;
int srcY;
for (int y = 0; y < newHeight; ++y) {
for (int x = 0; x < newWidth; ++x) {
srcX = (x * imgW) / newWidth;
srcY = (y * imgH) / newHeight;
destPixels[x + y * newWidth] = srcPixels[srcX + srcY * imgW];
}
}
return Image.createRGBImage(destPixels, newWidth, newHeight, true);
}
全部回答
- 1楼网友:悲观垃圾
- 2021-02-27 00:50
image srcimg = imageio.read(new fileinputstream(fnsrc) );//取源图
int width = 600; //假设要缩小到600点像素
int height = srcimg.getheight(null)*600/srcimg.getwidth(null);//按比例,将高度缩减
system.out.println("width: "+srcimg.getwidth(null));// 这几行是调试用
system.out.println("height: "+srcimg.getheight(null));
system.out.println("width2: "+width);
system.out.println("height2: "+height);
image smallimg =srcimg.getscaledinstance(width, height, image.scale_smooth);//缩小
我要举报
如以上问答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯