简体   繁体   中英

Combined re-scaling and color reduction of an image in Java?

Given a rectangular input image I'd like to create an output image of size 40x40 pixels using a maximum of 10 colors. Hence, the two operatons needed are re-scaling and color reduction.

The following ImageMagick command does the trick:

convert input.png -scale 40x40 -colors 10 output.png

How would you achieve the corresponding result in Java?

Shelling out to ImageMagick is not an option :-)

Something like this would work using JAI:

    // 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);
            ParameterBlock ParameterBlock pb = new ParameterBlock(); 
            ColorModel cm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.TYPE_YCbCr), new int[] {8}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
            pb.add(cm); 
            RenderedOp imgycc = JAI.create("ColorConvert", pb);
    }
    catch (FileNotFoundException e)
    {
    }

在jai.dev.java.net上查找Java Advanced Imaging(JAI)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM