编辑地图时发现第三方库只识别像素宽度为偶数的图片,读取奇数像素宽度图片时会出现乱码。写个代码将图片按像素宽度为偶数缩放:
import df.util.type.StringUtil;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.plaf.synth.SynthStyle;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.MathContext;
import java.net.URL;
import java.util.ArrayList;
public class ImageSwing {
private static void printf(Object obj) {
System.out.println("hai:::" + obj);
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ArrayList<String> fileList = readFileName("E:\\study\\PngPro\\out\\production\\PngPro\\source");
printf("得到文件数目 " + fileList.size());
printf("得到文件名 " + fileList.toString());
int icount = 0;
for (int i = 0; i < fileList.size(); i++) {
String srcName = fileList.get(i);
String srcPath = "./source/" + srcName;
URL resource = ImageSwing.class.getResource(srcPath);
printf(resource);
BufferedImage sourceImage = ImageIO.read(resource);
Integer wid = sourceImage.getWidth();
Integer height = sourceImage.getHeight();
if (wid % 2 == 1) {
Integer destW = ((wid / 2) + 1) * 2;
Integer destH = height;
BufferedImage dstImage = resizeImage(sourceImage, destW, destH);
/********** save到本地 *****************/
try {
String destPath = "E:\\study\\PngPro\\out\\production\\PngPro\\source\\save\\" + srcName;
ImageIO.write(dstImage, "png", new File(destPath));
icount++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
printf("修改的图片数目 " + icount);
}
/**
* 查找指定文件夹下文件
*
* @param dir
* @return
*/
public static ArrayList<String> readFileName(String dir) {
Integer dirCount = 0;
Integer fileCount = 0;
File file = new File(dir);
String[] list = file.list();
ArrayList<String> fileList = new ArrayList<String>();
for (int i = 0; i < list.length; i++) {
File f = new File(dir + "\\" + list[i]);
if (f.isFile()) {
fileCount++;
String filname = f.getName();
printf("file name fileCount[" + fileCount + "]=" + filname);
String[] sp = filname.split("\\.");//'.'号需要用转义字符表示
if (sp.length > 1 && sp[sp.length-1].equals("png")){
fileList.add(f.getName());
}
}
}
return fileList;
}
/**
* 变更图像为指定大小
*
* @param bufferedimage 目标图像
* @param w 宽
* @param h 高
* @return
*/
public static BufferedImage resizeImage(final BufferedImage bufferedimage,
final int w, final int h) {
int type = bufferedimage.getColorModel().getTransparency();
BufferedImage img;
Graphics2D graphics2d;
(graphics2d = (img = new BufferedImage(w, h, type))
.createGraphics()).setRenderingHint(
RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2d.drawImage(bufferedimage, 0, 0, w, h, 0, 0, bufferedimage
.getWidth(), bufferedimage.getHeight(), null);
graphics2d.dispose();
return img;
}
}