图片翻转
1.需求:照片使用前置摄像头拍摄,转正常照片
转换前:
public static void main(String[] args) {
File inputFile = new File("E:\\lswj\\230203103017950_877418.jpg");
File outputFile = new File("E:\\lswj\\output.jpg");
imageHorizontally(inputFile, outputFile);
imageVertically(inputFile, outputFile);
}
/**
* 前置摄像头照片转成正常照片
* @param inputFile
* @param outputFile
*/
public static void imageHorizontally(File inputFile, File outputFile) {
try {
BufferedImage inputImage = ImageIO.read(inputFile);
int width = inputImage.getWidth();
int height = inputImage.getHeight();
BufferedImage outputImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
outputImage.setRGB(x, y, inputImage.getRGB(width - x - 1, y));
}
}
ImageIO.write(outputImage, "PNG", outputFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 前置摄像头照片转成正常照片然后上下翻转
* @param inputFile
* @param outputFile
*/
public static void imageVertically(File inputFile, File outputFile) {
try {
BufferedImage inputImage = ImageIO.read(inputFile);
int width = inputImage.getWidth();
int height = inputImage.getHeight();
BufferedImage outputImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
outputImage.setRGB(x, y, inputImage.getRGB(x, height - y - 1));
}
}
ImageIO.write(outputImage, "PNG", outputFile);
} catch (Exception e) {
e.printStackTrace();
}
}
imageVertically方法转换后:
imageHorizontally方法转换后:
我本次需要的是imageHorizontally转换后的效果
上次提供的照片翻转代码经过实际检测,发现一个200K的照片翻转后的大小在4M左右,容量太大,修改为下面的方法
/**
* 图片镜像翻转
*
* @param file 原图片file文件
* @param target 翻转后图片输出路径
*/
public static File mirrorImage(File file, String target) {
BufferedImage image;
try {
image = ImageIO.read(file);
int width = image.getWidth();
int height = image.getHeight();
for (int j = 0; j < height; j++) {
int l = 0, r = width - 1;
while (l < r) {
int pl = image.getRGB(l, j);
int pr = image.getRGB(r, j);
image.setRGB(l, j, pr);
image.setRGB(r, j, pl);
l++;
r--;
}
}
file = new File(target);
String fileName = file.getName();
String fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
ImageIO.write(image, fileExtension, file);
} catch (IOException e) {
e.printStackTrace();
}
return file;
}