Java:将图像保存为JPEG 倾斜问题

标签 java c++ jpeg padding skew

我正在尝试将图像保存为 JPEG。当图像宽度是 4 的倍数时,下面的代码工作正常,但否则图像会倾斜。它与填充有关。当我调试时,通过用 0 填充每一行,我能够将图像正确保存为位图。但是,这不适用于 JPEG。

要记住的要点是我的图像表示为 bgr(蓝绿红各 1 个字节)字节数组,这是我从 native 调用接收到的。

byte[] data = captureImage(OpenGLCanvas.getLastFocused().getViewId(), x, y);
if (data.length != 3*x*y)
{
  // 3 bytes per pixel
  return false;
}

// create buffered image from raw data
DataBufferByte buffer = new DataBufferByte(data, 3*x*y);
ComponentSampleModel csm = new ComponentSampleModel(DataBuffer.TYPE_BYTE, x, y, 3, 3*x, new int[]{0,1,2} );
WritableRaster raster = Raster.createWritableRaster(csm, buffer, new Point(0,0));
BufferedImage buff_image = new BufferedImage(x, y, BufferedImage.TYPE_INT_BGR); // because windows goes the wrong way...
buff_image.setData(raster);

//save the BufferedImage as a jpeg
try
{
  File file = new File(file_name);
  FileOutputStream out = new FileOutputStream(file);

  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(buff_image);
  param.setQuality(1.0f, false);
  encoder.setJPEGEncodeParam(param);
  encoder.encode(buff_image);
  out.close();
  // or JDK 1.4
  // ImageIO.write(image, "JPEG", out);
}
catch (Exception ex)
{
  // Write permissions on "file_name"
  return false;
}

我也考虑过用 C++ 创建 JPEG,但是这方面的资料更少,但它仍然是一个选择。

非常感谢任何帮助。 里昂

最佳答案

感谢您的建议,但我已经设法解决了。

为了捕获图像,我在 C++ 中使用 WINGDIAPI HBITMAP WINAPI CreateDIBSection,然后 OpenGL 将绘制到该位图。不知道的是,位图中自动添加了填充,宽度不是 4 的倍数。

因此 Java 错误地解释了字节数组。

正确的方式是解释字节是

byte[] data = captureImage(OpenGLCanvas.getLastFocused().getViewId(), x, y);
int x_padding = x%4;
BufferedImage buff_image = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);

int val;
for (int j = 0; j < y; j++) 
{
  for (int i = 0; i < x; i++) 
  {
    val =  ( data[(i + j*x)*3 + j*x_padding + 2]& 0xff) + 
           ((data[(i + j*x)*3 + j*x_padding + 1]& 0xff) << 8) +
           ((data[(i + j*x)*3 + j*x_padding + 0]& 0xff) << 16);
    buff_image.setRGB(i, j, val);
  }
}

//save the BufferedImage as a jpeg
try
{
  File file = new File(file_name);
  FileOutputStream out = new FileOutputStream(file);

  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(buff_image);
  param.setQuality(1.0f, false);
  encoder.setJPEGEncodeParam(param);
  encoder.encode(buff_image);
  out.close();
}

关于Java:将图像保存为JPEG 倾斜问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4551867/

相关文章:

java - 如何找到 LocalDate java 之间的天数?

c++ - Qt Widget - 如何只捕获几个键盘键

c++ - 在 C++ 中重载删除运算符

c++ - 函数参数的多态性

ios - JPEG 保存到 ios 照片库后 DCT 系数发生变化

perl - 为什么我的图像在使用此 Perl CGI 脚本时会被剪裁?

java - HWPFDocument/XWPFDocument 新行

java - 如何使用 MigLayout?

java - 如何按字母顺序对名称数组列表进行排序,但以数字开头的名称必须排在最后

javascript - 在 HTML5 输入元素中接受 ".jpg-large"