Search in sources :

Example 1 with TranscodingHints

use of org.apache.batik.transcoder.TranscodingHints in project quick-media by liuyueyi.

the class PNGTranscoderImageIOWriteAdapter method writeImage.

/**
 * @throws TranscoderException
 * @see org.apache.batik.transcoder.image.PNGTranscoder.WriteAdapter#writeImage(org.apache.batik.transcoder.image.PNGTranscoder, java.awt.image.BufferedImage, org.apache.batik.transcoder.TranscoderOutput)
 */
public void writeImage(PNGTranscoder transcoder, BufferedImage img, TranscoderOutput output) throws TranscoderException {
    TranscodingHints hints = transcoder.getTranscodingHints();
    int n = -1;
    if (hints.containsKey(PNGTranscoder.KEY_INDEXED)) {
        n = ((Integer) hints.get(PNGTranscoder.KEY_INDEXED)).intValue();
        if (n == 1 || n == 2 || n == 4 || n == 8)
            // PNGEncodeParam.Palette can handle these numbers only.
            img = IndexImage.getIndexedImage(img, 1 << n);
    }
    ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor("image/png");
    ImageWriterParams params = new ImageWriterParams();
    /* NYI!!!!!
        PNGEncodeParam params = PNGEncodeParam.getDefaultEncodeParam(img);
        if (params instanceof PNGEncodeParam.RGB) {
            ((PNGEncodeParam.RGB)params).setBackgroundRGB
                (new int [] { 255, 255, 255 });
        }*/
    // If they specify GAMMA key with a value of '0' then omit
    // gamma chunk.  If they do not provide a GAMMA then just
    // generate an sRGB chunk. Otherwise supress the sRGB chunk
    // and just generate gamma and chroma chunks.
    /* NYI!!!!!!
        if (hints.containsKey(PNGTranscoder.KEY_GAMMA)) {
            float gamma = ((Float)hints.get(PNGTranscoder.KEY_GAMMA)).floatValue();
            if (gamma > 0) {
                params.setGamma(gamma);
            }
            params.setChromaticity(PNGTranscoder.DEFAULT_CHROMA);
        }  else {
            // We generally want an sRGB chunk and our encoding intent
            // is perceptual
            params.setSRGBIntent(PNGEncodeParam.INTENT_PERCEPTUAL);
        }*/
    float PixSzMM = transcoder.getUserAgent().getPixelUnitToMillimeter();
    int PixSzInch = (int) (25.4 / PixSzMM + 0.5);
    params.setResolution(PixSzInch);
    try {
        OutputStream ostream = output.getOutputStream();
        writer.writeImage(img, ostream, params);
        ostream.flush();
    } catch (IOException ex) {
        throw new TranscoderException(ex);
    }
}
Also used : TranscodingHints(org.apache.batik.transcoder.TranscodingHints) ImageWriterParams(org.apache.batik.ext.awt.image.spi.ImageWriterParams) TranscoderException(org.apache.batik.transcoder.TranscoderException) OutputStream(java.io.OutputStream) ImageWriter(org.apache.batik.ext.awt.image.spi.ImageWriter) IOException(java.io.IOException)

Example 2 with TranscodingHints

use of org.apache.batik.transcoder.TranscodingHints in project quick-media by liuyueyi.

the class PNGTranscoderInternalCodecWriteAdapter method writeImage.

/**
 * @throws TranscoderException
 * @see org.apache.batik.transcoder.image.PNGTranscoder.WriteAdapter#writeImage(org.apache.batik.transcoder.image.PNGTranscoder, java.awt.image.BufferedImage, org.apache.batik.transcoder.TranscoderOutput)
 */
public void writeImage(PNGTranscoder transcoder, BufferedImage img, TranscoderOutput output) throws TranscoderException {
    TranscodingHints hints = transcoder.getTranscodingHints();
    int n = -1;
    if (hints.containsKey(PNGTranscoder.KEY_INDEXED)) {
        n = ((Integer) hints.get(PNGTranscoder.KEY_INDEXED)).intValue();
        if (n == 1 || n == 2 || n == 4 || n == 8)
            // PNGEncodeParam.Palette can handle these numbers only.
            img = IndexImage.getIndexedImage(img, 1 << n);
    }
    PNGEncodeParam params = PNGEncodeParam.getDefaultEncodeParam(img);
    if (params instanceof PNGEncodeParam.RGB) {
        ((PNGEncodeParam.RGB) params).setBackgroundRGB(new int[] { 255, 255, 255 });
    }
    // and just generate gamma and chroma chunks.
    if (hints.containsKey(PNGTranscoder.KEY_GAMMA)) {
        float gamma = ((Float) hints.get(PNGTranscoder.KEY_GAMMA)).floatValue();
        if (gamma > 0) {
            params.setGamma(gamma);
        }
        params.setChromaticity(PNGTranscoder.DEFAULT_CHROMA);
    } else {
        // We generally want an sRGB chunk and our encoding intent
        // is perceptual
        params.setSRGBIntent(PNGEncodeParam.INTENT_PERCEPTUAL);
    }
    float PixSzMM = transcoder.getUserAgent().getPixelUnitToMillimeter();
    // num Pixs in 1 Meter
    int numPix = (int) ((1000 / PixSzMM) + 0.5);
    // 1 means 'pix/meter'
    params.setPhysicalDimension(numPix, numPix, 1);
    try {
        OutputStream ostream = output.getOutputStream();
        PNGImageEncoder pngEncoder = new PNGImageEncoder(ostream, params);
        pngEncoder.encode(img);
        ostream.flush();
    } catch (IOException ex) {
        throw new TranscoderException(ex);
    }
}
Also used : TranscodingHints(org.apache.batik.transcoder.TranscodingHints) TranscoderException(org.apache.batik.transcoder.TranscoderException) OutputStream(java.io.OutputStream) IOException(java.io.IOException)

Example 3 with TranscodingHints

use of org.apache.batik.transcoder.TranscodingHints in project mage by magefree.

the class SvgUtils method loadSVG.

/**
 * Load svg file content as image
 *
 * @param svgFile               content (can be resource or file)
 * @param svgInfo               info to show in logs or errors
 * @param cssFileName           css settings
 * @param cssAdditionalSettings additional css settings (warning, if you change additional settings then css file must be re-created)
 * @param resizeToWidth         image size
 * @param resizeToHeight        image size
 * @param useShadow             draw image with shadow (not implemented)
 * @return can return null on error (some linux systems can have compatibility problem with different java/svg libs)
 * @throws IOException
 */
public static BufferedImage loadSVG(InputStream svgFile, String svgInfo, String cssFileName, String cssAdditionalSettings, int resizeToWidth, int resizeToHeight, boolean useShadow) throws IOException {
    if (svgFile == null) {
        throw new IllegalArgumentException("Empty svg data or unknown file");
    }
    // load SVG image
    // base loader code: https://stackoverflow.com/questions/11435671/how-to-get-a-buffererimage-from-a-svg
    // resize code: https://vibranttechie.wordpress.com/2015/05/15/svg-loading-to-javafx-stage-and-auto-scaling-when-stage-resize/
    // TODO: implement shadow drawing
    useShadow = false;
    if (useShadow && ((resizeToWidth <= 0) || (resizeToHeight <= 0))) {
        throw new IllegalArgumentException("Must use non zero sizes for shadow");
    }
    final BufferedImage[] imagePointer = new BufferedImage[1];
    // css settings for svg
    SvgUtils.prepareCss(cssFileName, cssAdditionalSettings, false);
    File cssFile = new File(SvgUtils.getSvgTempFile(cssFileName));
    TranscodingHints transcoderHints = new TranscodingHints();
    // resize
    int shadowX = 0;
    int shadowY = 0;
    if (useShadow) {
        // shadow size (16px image: 1px left, 2px bottom)
        shadowX = 1 * Math.round(1f / 16f * resizeToWidth);
        shadowY = 2 * Math.round(1f / 16f * resizeToHeight);
        resizeToWidth = resizeToWidth - shadowX;
        resizeToHeight = resizeToHeight - shadowY;
    }
    if (resizeToWidth > 0) {
        // your image width
        transcoderHints.put(ImageTranscoder.KEY_WIDTH, (float) resizeToWidth);
    }
    if (resizeToHeight > 0) {
        // your image height
        transcoderHints.put(ImageTranscoder.KEY_HEIGHT, (float) resizeToHeight);
    }
    transcoderHints.put(ImageTranscoder.KEY_XML_PARSER_VALIDATING, Boolean.FALSE);
    transcoderHints.put(ImageTranscoder.KEY_DOM_IMPLEMENTATION, SVGDOMImplementation.getDOMImplementation());
    transcoderHints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT_NAMESPACE_URI, SVGConstants.SVG_NAMESPACE_URI);
    transcoderHints.put(ImageTranscoder.KEY_DOCUMENT_ELEMENT, "svg");
    transcoderHints.put(ImageTranscoder.KEY_USER_STYLESHEET_URI, cssFile.toURI().toString());
    try {
        TranscoderInput input = new TranscoderInput(svgFile);
        ImageTranscoder t = new ImageTranscoder() {

            @Override
            public BufferedImage createImage(int w, int h) {
                return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            }

            @Override
            public void writeImage(BufferedImage image, TranscoderOutput out) {
                imagePointer[0] = image;
            }
        };
        t.setTranscodingHints(transcoderHints);
        t.transcode(input, null);
    } catch (Exception e) {
        throw new IOException("Can't load svg file: " + svgInfo + " , reason: " + e.getMessage());
    }
    BufferedImage originImage = imagePointer[0];
    if (useShadow && (originImage.getWidth() > 0)) {
        // draw shadow
        // origin image was reduces in sizes to fit shadow
        // see https://stackoverflow.com/a/40833715/1276632
        // a filter which converts all colors except 0 to black
        ImageProducer prod = new FilteredImageSource(originImage.getSource(), new RGBImageFilter() {

            @Override
            public int filterRGB(int x, int y, int rgb) {
                if (rgb == 0) {
                    return 0;
                } else {
                    return 0xff000000;
                }
            }
        });
        // create whe black image
        Image shadow = Toolkit.getDefaultToolkit().createImage(prod);
        // result
        BufferedImage result = new BufferedImage(originImage.getWidth() + shadowX, originImage.getHeight() + shadowY, originImage.getType());
        Graphics2D g = (Graphics2D) result.getGraphics();
        // draw shadow with offset (left bottom)
        g.drawImage(shadow, -1 * shadowX, shadowY, null);
        // draw original image
        g.drawImage(originImage, 0, 0, null);
        return result;
    } else {
        // return origin image without shadow
        return originImage;
    }
/*
        BufferedImage base = GraphicsUtilities.createCompatibleTranslucentImage(w, h);
        Graphics2D g2 = base.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRoundRect(0, 0, image.getWidth(), image.getHeight(), 10, 10);
        g2.dispose();

        ShadowRenderer renderer = new ShadowRenderer(shadowSize, 0.5f,
                Color.GRAY);
        return renderer.createShadow(base);
         */
// imagePointer[0];
}
Also used : ImageTranscoder(org.apache.batik.transcoder.image.ImageTranscoder) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) BufferedImage(java.awt.image.BufferedImage) IOException(java.io.IOException) RGBImageFilter(java.awt.image.RGBImageFilter) TranscoderOutput(org.apache.batik.transcoder.TranscoderOutput) TranscodingHints(org.apache.batik.transcoder.TranscodingHints) TranscoderInput(org.apache.batik.transcoder.TranscoderInput) ImageProducer(java.awt.image.ImageProducer) FilteredImageSource(java.awt.image.FilteredImageSource) File(java.io.File)

Example 4 with TranscodingHints

use of org.apache.batik.transcoder.TranscodingHints in project quick-media by liuyueyi.

the class TIFFTranscoderImageIOWriteAdapter method writeImage.

/**
 * @throws TranscoderException
 * @see org.apache.batik.transcoder.image.TIFFTranscoder.WriteAdapter#writeImage(TIFFTranscoder, java.awt.image.BufferedImage, org.apache.batik.transcoder.TranscoderOutput)
 */
public void writeImage(TIFFTranscoder transcoder, BufferedImage img, TranscoderOutput output) throws TranscoderException {
    TranscodingHints hints = transcoder.getTranscodingHints();
    ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor("image/tiff");
    ImageWriterParams params = new ImageWriterParams();
    float PixSzMM = transcoder.getUserAgent().getPixelUnitToMillimeter();
    int PixSzInch = (int) (25.4 / PixSzMM + 0.5);
    params.setResolution(PixSzInch);
    if (hints.containsKey(TIFFTranscoder.KEY_COMPRESSION_METHOD)) {
        String method = (String) hints.get(TIFFTranscoder.KEY_COMPRESSION_METHOD);
        // Values set here as defined in TIFFImageWriteParam of JAI Image I/O Tools
        if ("packbits".equals(method)) {
            params.setCompressionMethod("PackBits");
        } else if ("deflate".equals(method)) {
            params.setCompressionMethod("Deflate");
        } else if ("lzw".equals(method)) {
            params.setCompressionMethod("LZW");
        } else if ("jpeg".equals(method)) {
            params.setCompressionMethod("JPEG");
        } else {
        // nop
        }
    }
    try {
        OutputStream ostream = output.getOutputStream();
        int w = img.getWidth();
        int h = img.getHeight();
        SinglePixelPackedSampleModel sppsm;
        sppsm = (SinglePixelPackedSampleModel) img.getSampleModel();
        int bands = sppsm.getNumBands();
        int[] off = new int[bands];
        for (int i = 0; i < bands; i++) off[i] = i;
        SampleModel sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, w, h, bands, w * bands, off);
        RenderedImage rimg = new FormatRed(GraphicsUtil.wrap(img), sm);
        writer.writeImage(rimg, ostream, params);
        ostream.flush();
    } catch (IOException ex) {
        throw new TranscoderException(ex);
    }
}
Also used : PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) OutputStream(java.io.OutputStream) ImageWriter(org.apache.batik.ext.awt.image.spi.ImageWriter) SinglePixelPackedSampleModel(java.awt.image.SinglePixelPackedSampleModel) IOException(java.io.IOException) PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) SampleModel(java.awt.image.SampleModel) SinglePixelPackedSampleModel(java.awt.image.SinglePixelPackedSampleModel) TranscodingHints(org.apache.batik.transcoder.TranscodingHints) ImageWriterParams(org.apache.batik.ext.awt.image.spi.ImageWriterParams) FormatRed(org.apache.batik.ext.awt.image.rendered.FormatRed) TranscoderException(org.apache.batik.transcoder.TranscoderException) RenderedImage(java.awt.image.RenderedImage)

Aggregations

IOException (java.io.IOException)4 TranscodingHints (org.apache.batik.transcoder.TranscodingHints)4 OutputStream (java.io.OutputStream)3 TranscoderException (org.apache.batik.transcoder.TranscoderException)3 ImageWriter (org.apache.batik.ext.awt.image.spi.ImageWriter)2 ImageWriterParams (org.apache.batik.ext.awt.image.spi.ImageWriterParams)2 BufferedImage (java.awt.image.BufferedImage)1 FilteredImageSource (java.awt.image.FilteredImageSource)1 ImageProducer (java.awt.image.ImageProducer)1 PixelInterleavedSampleModel (java.awt.image.PixelInterleavedSampleModel)1 RGBImageFilter (java.awt.image.RGBImageFilter)1 RenderedImage (java.awt.image.RenderedImage)1 SampleModel (java.awt.image.SampleModel)1 SinglePixelPackedSampleModel (java.awt.image.SinglePixelPackedSampleModel)1 File (java.io.File)1 FormatRed (org.apache.batik.ext.awt.image.rendered.FormatRed)1 TranscoderInput (org.apache.batik.transcoder.TranscoderInput)1 TranscoderOutput (org.apache.batik.transcoder.TranscoderOutput)1 ImageTranscoder (org.apache.batik.transcoder.image.ImageTranscoder)1