【发布时间】:2016-11-08 23:00:06
【问题描述】:
如果有人可以帮助我,我会遇到一个小问题,我会很高兴。 我正在尝试进行下一步操作
- 读取 BMP 图像
- 将图像转换为字节[]
- 将图像旋转 90 度(字节数组)
- 并在某个文件夹中写入新图像
我的问题是......在我尝试编写新图像的那一刻,我的 BMP 标头出现了一些问题,我不知道为什么。如果有人知道答案,请给我一些建议。
将图片转换成字节[]
private static byte[] convertAnImageToPixelsArray(File file) throws FileNotFoundException {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
try {
for (int readNum; (readNum = fis.read(buf)) != -1; ) {
bos.write(buf, 0, readNum);
}
} catch (IOException ex) {
Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
}
return bos.toByteArray();
}
旋转
private static byte[] rotate(double angle, byte[] pixels, int width, int height) {
final double radians = Math.toRadians(angle), cos = Math.cos(radians), sin = Math.sin(radians);
final byte[] pixels2 = new byte[pixels.length];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
final int
centerx = width / 2,
centery = height / 2,
m = x - centerx,
n = y - centery,
j = ((int) (m * cos + n * sin)) + centerx,
k = ((int) (n * cos - m * sin)) + centery;
if (j >= 0 && j < width && k >= 0 && k < height)
pixels2[(y * width + x)] = pixels[(k * width + j)];
}
}
arraycopy(pixels2, 0, pixels, 0, pixels.length);
return pixels2;
}
将字节[]转换为图片
private static void convertArrayPixelsIntoImage(byte[] bytes) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("bmp");
ImageReader reader = (ImageReader) readers.next();
Object source = bis;
ImageInputStream iis = ImageIO.createImageInputStream(source);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Image image = reader.read(0, param);
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);
File imageFile = new File("Images/Output.bmp");
ImageIO.write(bufferedImage, "bmp", imageFile);
}
主要:
public static void main(String[] args) throws IOException {
File file = new File("Images/Input-1.bmp");
Image img = ImageIO.read(file);
convertArrayPixelsIntoImage(rotate(90,convertAnImageToPixelsArray(file),img.getWidth(null),img.getHeight(null)));
}
这是错误消息:
线程“main”javax.imageio.IIOException 中的异常:无法读取图像头。
有什么建议吗?
【问题讨论】:
-
你如何调用这些方法?请显示您调用它们的方法。
-
我已经添加了main函数。
-
您正在旋转整个图像文件的内容,包括标题,因此您正在破坏标题。但是为什么还要读两遍呢?您使用
ImageIO.read和convertAnImageToPixelsArray读取图像 - 这是多余的。
标签: java arrays image image-processing bmp