大多数图像格式在像素数据之前都有标题信息,因此当您阅读这些类型的文件时,您需要考虑到这一点......
坦率地说,尽可能地依赖预先存在的库要容易得多。
ImageIO
允许您读取和写入多种不同的文件格式,包括 BMP。
看一眼
下一个决定是 - 您自己转换图像还是使用预先存在的过滤器。你必须做一些你自己的指标,但在过去,我发现图像的像素操作很慢,至少比内置过滤器慢......
原始、手动灰度、自动/过滤灰度
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class GrayScaleImage {
public static void main(String[] args) {
new GrayScaleImage();
}
public GrayScaleImage() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(0, 3));
try {
BufferedImage master = ImageIO.read(new File("/path/to/file.bmp"));
BufferedImage gray = ImageIO.read(new File("/path/to/file.bmp"));
// Manual manipulation...
for (int x = 0; x < gray.getWidth(); x++) {
for (int y = 0; y < gray.getHeight(); y++) {
Color color = new Color(gray.getRGB(x, y));
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
red = green = blue = (int)(red * 0.299 + green * 0.587 + blue * 0.114);
color = new Color(red, green, blue);
int rgb = color.getRGB();
gray.setRGB(x, y, rgb);
}
}
BufferedImage grayScale = ImageIO.read(new File("/path/to/file.bmp"));
// Automatic converstion....
ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
op.filter(grayScale, grayScale);
add(new JLabel(new ImageIcon(master)));
add(new JLabel(new ImageIcon(gray)));
add(new JLabel(new ImageIcon(grayScale)));
} catch (IOException ex) {
Logger.getLogger(GrayScaleImage.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
现在,编写图像(上面没有演示)就像...
ImageIO.write(grayScale, "BMP", new File("/path/to/grayscale file.bmp"));