原始数据为JPEG格式 - JAVA

时间:2012-09-25 04:18:38

标签: java image flex jpeg flex-mobile

我尝试使用JPEGEncoder将原始数据ByteArray转换为JPEG格式,但它在移动设备上的速度太慢(我在移动设备上测试过它)。我怎样才能在java中做同样的事情?我将原始数据字节发送到java并使用java将其编码为JPEG - 我在com.sun。*中尝试了一些作为JpegImageEncoder,但它在jdk7中被折旧了。我如何在java中执行此操作或者已经完成此类操作的Flex移动开发人员的任何建议?

更新:我尝试了以下代码,但我得到了一个奇怪的结果:

public void rawToJpeg(byte[] rawBytes, int width, int height, File outputFile){

        try{

            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

            int count = 0; 
            for(int h=0;h<height;h++){
                for(int w=0;w<width;w++){
                    bi.setRGB(w, h, rawBytes[count++]);
                }
            }


            Graphics2D ig2 = bi.createGraphics();

            Iterator imageWriters = ImageIO.getImageWritersByFormatName("jpeg");
            ImageWriter imageWriter = (ImageWriter) imageWriters.next(); 

            ImageOutputStream ios = ImageIO.createImageOutputStream(outputFile);
            imageWriter.setOutput(ios);
            imageWriter.write(bi);


        }catch(Exception ex){
            ex.printStackTrace();
        }


    }

结果:enter image description here

P.S应该是我的照片顺便说一句:)

4 个答案:

答案 0 :(得分:1)

为什么不将ByteArrayInputStreamImageIO一起使用?

您可以在API中找到有关ImageIO的更多信息。

public static void rawToJpeg(byte[] bytes, File outputFile) {
    try {
        BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));
        ImageIO.write(img, "jpg", outputFile);
    } catch (IOException e) {
        // Handle exception
    }
}

答案 1 :(得分:0)

bi.setRGB采用4字节“int”值,即ARGB 0xAARRGGBB

然后将字节偏移计数器递增1,因此下一个像素将获得0xRRGGBBAA,然后是0xGGBBAARR,依此类推。

假设您传递的byte []是正确的4字节格式,您需要每次添加4到“count”,或者更改传递给int [](这实际上更正确) ,因为它确实包含int值)。

答案 2 :(得分:0)

您好我面临同样的问题,我设置宽度和高度值为硬编码让我们说(300,300)导致类似的输出。然后我引用了这个链接。 Raw byte[] to jpeg image您可以忽略其中的位图部分。我假设你也在硬编码宽度和高度值。

答案 3 :(得分:0)

您可以尝试通过此

替换for循环
for(int w = 0; w < width; w++)
{
    for(int h = 0; h < height; h++)
    {
            //alpha should be eiter 0 or 255
            //if you use the wrong value your image will be transparent

            int alpha = 0 << 8*3;
            int red = rawBytes[count*3 + 0] << 8*2;
            int green = rawBytes[count*3 + 1] << 8*1;
            int blue = rawBytes[count*3 + 2] << 8*0;

            int color = alpha + red + green + blue;

            //color is an int with the format of TYPE_INT_ARGB (0xAARRGGBB)

            bi.setRGB(w, h, color);
            count += 3;
    }
}

您的代码可能出错的地方:

  1. 您通常逐行逐行编写

  2. 您需要读取3个字节并构建一个int而不是直接在Pixel(TYPE_INT_ARGB)中写入字节

  3. 此链接说明了TYPE_INT_ARGB:TYPE_INT_RGB的格式和TYPE_INT_ARGB

    我希望这有点帮助,而不是太混乱=)

相关问题