我做了以下示例,我无法弄清楚它为什么不起作用。
但图像仍未在磁盘上更改。
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class example
{
public static void main(String[] args)
{
try
{
// load a jpg file
File imageFile = getFile();
// Make a Buffered Image from it
BufferedImage img = ImageIO.read(imageFile);
// for every pixel in the image
for (int x = 0; x < img.getWidth(); x++)
for (int y = 0; y < img.getHeight(); y++)
// check if the RGB integer is an odd number
if (img.getRGB(x, y) % 2 != 0)
// make it an even number if it is odd (the OCD god demands it!)
img.setRGB(x, y, img.getRGB(x, y) - 1);
// Write the OCD friendly version to the file
System.out.println("Was overwritten: " + ImageIO.write(img, "jpg", imageFile));
System.out.println();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Select the same file again
imageFile = getFile();
// Make the bufferedImage from it
img = ImageIO.read(imageFile);
// for every pixel in the image
for (int x = 0; x < img.getWidth(); x++)
for (int y = 0; y < img.getHeight(); y++)
// check if the RGB integer is an odd number
if (img.getRGB(x, y) % 2 != 0)
{
// Report the failing
System.out.println("It didn't work :(");
// Stop the loop
x = img.getWidth();
y = img.getHeight();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static File getFile()
{
// set up a file chooser that only accepts jpgs
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("JPG Images only", "jpg"));
// This will represent our loaded file
File imageFile = null;
// Select a file
chooser.showOpenDialog(null);
imageFile = chooser.getSelectedFile();
// Check we can do stuff to this file
System.out.println("Exists: " + imageFile.exists());
System.out.println("Can Read: " + imageFile.canRead());
System.out.println("Can Write: " + imageFile.canWrite());
System.out.println();
return imageFile;
}
}
答案 0 :(得分:1)
它被覆盖,你只是没有用你的视觉检测到
眼睛。这是因为您只需将RGB值更改为1.
for (int x = 0; x < img.getWidth(); x++)
for (int y = 0; y < img.getHeight(); y++)
// check if the RGB integer is an odd number
if (img.getRGB(x, y) % 2 != 0)
// make it an even number if it is odd (the OCD god demands it!)
img.setRGB(x, y, 0); /// A ///
像我一样更改此行/// A ///
,您会看到它被覆盖。
当然,这也取决于您正在测试的图片。
如果img.getRGB(x, y)
从不奇怪,则永远不会执行img.setRGB
。