我是Java语言的初学者,我需要使用代码(编写灰度jpeg图像)。我搜索了很长时间,但是我无法弄清楚现在有什么问题。
public static boolean writeImage(String inputFileName, String outputFileName, int[][][] imageData)
{
BufferedImage inputImage = MyImageReader.readImageIntoBufferedImage( inputFileName );
if ( inputImage == null )
{
System.out.println(" Could not open input image.");
return false;
}
BufferedImage outputImage = new BufferedImage( inputImage.getWidth(), inputImage.getHeight(),
inputImage.getType() );
WritableRaster outputRaster, inputRaster;
inputRaster = inputImage.getRaster();
outputRaster = inputRaster.createCompatibleWritableRaster();
int band = 0;
int numbands = outputRaster.getNumBands();
int height, width;
height = outputRaster.getHeight();
width = outputRaster.getWidth();
int[] pixelData = new int[ 1 ];
for ( int y = 0; y < height; y++ )
for ( int x = 0; x < width; x++ )
{
for ( band = 0; band < 1; band++ )
{
pixelData[ 0 ] = imageData[0][y][x];
}
outputRaster.setPixel(x, y, pixelData );
}
outputImage.setData( outputRaster );
File outputFile = new File( outputFileName );
try
{
if ( !ImageIO.write( outputImage, "jpg", outputFile ))
{
System.out.println("Could not find image format for output image.");
return false;
}
}
catch ( Exception e )
{
System.out.println("Could not write output file.");
return false;
}
return true;
}
我正在使用上述代码。该代码似乎通过从输入JPEG文件复制属性来创建一个writableraste,因此,输出JPEG文件将具有相同的大小。
我正在做的是在灰色缩放的光栅值上进行一些图像处理并将其保存为JPEG文件。
当我使用简单的4x4情况进行测试时,结果如下。
输入数组要保存在(高度,宽度)坐标
中1 2 3 4
5 6 7 8
15 16 17 18
25 26 27 28
当我加载保存的文件时,它显示为(高度,宽度)坐标
2 3 4 5
3 4 5 6
15 15 16 17
25 26 27 28
这怎么可能?我不知道怎么了。事实证明,图像读取器是安全的。我是从Oracle上运行的JDK 1.7,但原始代码可能是在过去写的。但我希望这不会是问题。
谢谢!
如果您能够使用第三方库,并决定利用imgscalr(Apache 2,开源和小型 - 一个类),则可以在您的中间删除所有复杂代码实施,看起来像这样:
import org.imgscalr.Scalr.*;
public static boolean writeImage(String inputFileName, String outputFileName)
{
BufferedImage inputImage = MyImageReader.readImageIntoBufferedImage( inputFileName );
if ( inputImage == null )
{
System.out.println(" Could not open input image.");
return false;
}
// This replaces everything in the middle of your original impl.
BufferedImage outputImage = apply(inputImage, Scalr.OP_GRAYSCALE);
File outputFile = new File( outputFileName );
try
{
if ( !ImageIO.write( outputImage, "jpg", outputFile ))
{
System.out.println("Could not find image format for output image.");
return false;
}
}
catch ( Exception e )
{
System.out.println("Could not write output file.");
return false;
}
return true;
}
关键是应用方法调用(将预定义的灰度OP应用于图像)。