JAI Change JPEG Resolution

给你一囗甜甜゛ 提交于 2019-12-11 12:28:45

问题


I am having difficulty using the Java JAI (Java Advance Imaging) API to change the resolution of a JPEG image from lets say 1024x800 to 512x400.

I have played around with the API and keep getting stream or java.lang.OutOfMemory exceptions.

Anyone with a working example.


回答1:


Here's a working example, supplied on an "as is" basis with no warranty :)

BufferedImage scaleImage(BufferedImage sourceImage, int scaledWidth) {
   float scale = scaledWidth / (float) sourceImage.getWidth();
   int scaledHeight = (int) (sourceImage.getHeight() * scale);
   Image scaledImage = sourceImage.getScaledInstance(
      scaledWidth, 
      scaledHeight, 
      Image.SCALE_AREA_AVERAGING
   );

   BufferedImage bufferedImage = new BufferedImage(
      scaledImage.getWidth(null), 
      scaledImage.getHeight(null), 
      BufferedImage.TYPE_INT_RGB
   );
   Graphics g = bufferedImage.createGraphics();
   g.drawImage(scaledImage, 0, 0, null);
   g.dispose();

   return bufferedImage;
}



回答2:


Here's one using JAI

public void resize(String filename, RenderedOp image, double wScale, double hScale)
{
    // now resize the image
    ParameterBlock pb = new ParameterBlock();
    pb.addSource(image); // The source image
    pb.add(wScale); // The xScale
    pb.add(hScale); // The yScale
    pb.add(0.0F); // The x translation
    pb.add(0.0F); // The y translation

    RenderingHints hints = new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);       
    RenderedOp resizedImage = JAI.create("SubsampleAverage", pb, hints);

    // lastly, write the newly-resized image to an
    // output stream, in a specific encoding
    try
    {
        FileOutputStream fos = new FileOutputStream(new File(filename));
        JAI.create("encode", resizedImage, fos, getImageType(filename), null);
    }
    catch (FileNotFoundException e)
    {
    }
}


来源:https://stackoverflow.com/questions/1324106/jai-change-jpeg-resolution

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!