Java Examples for java.awt.image.BufferedImageOp

The following java examples will help you to understand the usage of java.awt.image.BufferedImageOp. These source code samples are taken from different open source projects.

Example 1
Project: Petris-master  File: BlurFilter2.java View source code
public BufferedImage processImage(BufferedImage image) {
    /*float[] blurMatrix = { 0.0f / 1.0f, 1.0f / 8.0f, 0.0f / 1.0f, 
				1.0f / 8.0f, 1.0f / 2.0f, 1.0f / 8.0f, 
				0.0f / 1.0f, 1.0f / 8.0f, 0.0f / 1.0f };*/
    float[] matrix = new float[25];
    for (int i = 0; i < 25; i++) matrix[i] = 1.0f / 25.0f;
    BufferedImageOp blurFilter = new ConvolveOp(new Kernel(5, 5, matrix), ConvolveOp.EDGE_NO_OP, null);
    return blurFilter.filter(image, null);
}
Example 2
Project: cms-ce-master  File: FilterCommand.java View source code
public final ImageFilter build(BuilderContext context, Object[] args) {
    Object filter = doBuild(context, args);
    if (filter instanceof BufferedImageOp) {
        return wrap((BufferedImageOp) filter);
    } else if (filter instanceof ImageFilter) {
        return (ImageFilter) filter;
    } else if (filter instanceof java.awt.image.ImageFilter) {
        return wrap((java.awt.image.ImageFilter) filter);
    } else {
        return null;
    }
}
Example 3
Project: common_utils-master  File: AbstractFilterFactory.java View source code
public BufferedImage applyFilters(BufferedImage source) {
    BufferedImage dest = source;
    for (BufferedImageOp filter : getFilters()) {
        dest = filter.filter(dest, null);
    }
    int x = (source.getWidth() - dest.getWidth()) / 2;
    int y = (source.getHeight() - dest.getHeight()) / 2;
    source = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
    source.getGraphics().drawImage(dest, x, y, null);
    return source;
}
Example 4
Project: dreampie-master  File: AbstractFilterFactory.java View source code
public BufferedImage applyFilters(BufferedImage source) {
    BufferedImage dest = source;
    for (BufferedImageOp filter : getFilters()) {
        dest = filter.filter(dest, null);
    }
    int x = (source.getWidth() - dest.getWidth()) / 2;
    int y = (source.getHeight() - dest.getHeight()) / 2;
    source = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
    source.getGraphics().drawImage(dest, x, y, null);
    return source;
}
Example 5
Project: kisso-master  File: TestPatchcaPNG.java View source code
/**
	 * 测试
	 * <p>
	 * 执行�生�图片 test_patchca.png 当�项目目录下
	 * </p>
	 */
public static void main(String[] args) throws IOException {
    File dir = new File(System.getProperty("user.dir"));
    if (!dir.exists()) {
        dir.mkdir();
    }
    ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
    //验��宽高
    //		cs.setWidth(119);
    //		cs.setHeight(42);
    //设置 6 �自适应验��
    //		AdaptiveRandomWordFactory arw = new AdaptiveRandomWordFactory();
    //		arw.setMinLength(6);
    //		arw.setMaxLength(6);
    //		cs.setWordFactory(arw);
    //字符大�设置
    //		RandomFontFactory rf = new RandomFontFactory();
    //		rf.setMinSize(28);
    //		rf.setMaxSize(32);
    //		cs.setFontFactory(rf);
    //文本渲染
    //		cs.setTextRenderer(new RandomYBestFitTextRenderer());
    //设置一个�一颜色字体
    cs.setColorFactory(new SingleColorFactory(new Color(59, 162, 9)));
    //		cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
    //图片滤镜设置
    ConfigurableFilterFactory filterFactory = new ConfigurableFilterFactory();
    List<BufferedImageOp> filters = new ArrayList<BufferedImageOp>();
    //摆动干扰
    WobbleImageOp wio = new WobbleImageOp();
    wio.setEdgeMode(AbstractImageOp.EDGE_CLAMP);
    wio.setxAmplitude(2.0);
    wio.setyAmplitude(1.0);
    filters.add(wio);
    //曲线干扰
    //		CurvesImageOp cio = new CurvesImageOp();
    //		cio.setColorFactory(new SingleColorFactory(new Color(59, 162, 9)));
    //		cio.setEdgeMode(AbstractImageOp.EDGE_ZERO);
    //		cio.setStrokeMax(0.3f);
    //		cio.setStrokeMin(0.1f);
    //		filters.add(cio);
    filterFactory.setFilters(filters);
    cs.setFilterFactory(filterFactory);
    //椭圆形干扰背景
    cs.setBackgroundFactory(new OvalNoiseBackgroundFactory());
    //线形干扰背景
    //		cs.setBackgroundFactory(new LineNoiseBackgroundFactory());
    FileOutputStream fos = new FileOutputStream(new File(dir, "test_patchca.png"));
    EncoderHelper.getChallangeAndWriteImage(cs, "png", fos);
    fos.close();
}
Example 6
Project: patchca-master  File: AbstractFilterFactory.java View source code
public BufferedImage applyFilters(BufferedImage source) {
    BufferedImage dest = source;
    for (BufferedImageOp filter : getFilters()) {
        dest = filter.filter(dest, null);
    }
    int x = (source.getWidth() - dest.getWidth()) / 2;
    int y = (source.getHeight() - dest.getHeight()) / 2;
    source = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
    source.getGraphics().drawImage(dest, x, y, null);
    return source;
}
Example 7
Project: Resty-master  File: AbstractFilterFactory.java View source code
public BufferedImage applyFilters(BufferedImage source) {
    BufferedImage dest = source;
    for (BufferedImageOp filter : getFilters()) {
        dest = filter.filter(dest, null);
    }
    int x = (source.getWidth() - dest.getWidth()) / 2;
    int y = (source.getHeight() - dest.getHeight()) / 2;
    source = new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
    source.getGraphics().drawImage(dest, x, y, null);
    return source;
}
Example 8
Project: batik-master  File: SVGGraphics2D.java View source code
/**
     * Renders a <code>BufferedImage</code> that is
     * filtered with a
     * {@link BufferedImageOp}.
     * The rendering attributes applied include the <code>Clip</code>,
     * <code>Transform</code>
     * and <code>Composite</code> attributes.  This is equivalent to:
     * <pre>
     * img1 = op.filter(img, null);
     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
     * </pre>
     * @param op the filter to be applied to the image before rendering
     * @param img the <code>BufferedImage</code> to be rendered
     * @param x the x coordinate in user space where the upper left
     *          corner of the image is rendered
     * @param y the y coordinate in user space where the upper left
     *          corner of the image is rendered
     * @see #setTransform(AffineTransform)
     * @see #setComposite(java.awt.Composite)
     * @see #setClip(Shape)
     */
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    //
    // Only convert if the input image is of type sRGB
    // non-premultiplied
    //
    /*if(img.getType() == BufferedImage.TYPE_INT_ARGB){
            //
            // There are two special cases: AffineTransformOp and
            // ColorConvertOp. If the input op is not one of these
            // two, then SVGBufferedImageOp is requested to map the
            // filter to an SVG equivalent.
            //
            if(op instanceof AffineTransformOp){
                AffineTransformOp transformOp = (AffineTransformOp)op;
                AffineTransform transform = transformOp.getTransform();

                if(transform.getDeterminant() != 0){
                    AffineTransform inverseTransform = null;
                    try{
                        inverseTransform = transform.createInverse();
                    }catch(NoninvertibleTransformException e){
                        // This should never happen since we checked the
                        // matrix determinant
                        throw new SVGGraphics2DRuntimeException(ERR_UNEXPECTED);
                    }
                    gc.transform(transform);
                    drawImage(img, x, y, null);
                    gc.transform(inverseTransform);
                }
                else{
                    AffineTransform savTransform =
                    new AffineTransform(gc.getTransform());
                    gc.transform(transform);
                    drawImage(img, x, y, null);
                    gc.setTransform(savTransform);
                }
            }
            else if(op instanceof ColorConvertOp){
                img = op.filter(img, null);
                drawImage(img, x, y, null);
            }
            else{
                //
                // Try and convert to an SVG filter
                //
                SVGFilterDescriptor filterDesc =
                domTreeManager.getFilterConverter().toSVG(op, null);
                if(filterDesc != null){
                //
                // Because other filters may be needed to represent the
                // composite that applies to this image, a group is created that
                // contains the image element.
                //
                Element imageElement =
                getDOMFactory().
                createElementNS(SVG_NAMESPACE_URI, SVG_IMAGE_TAG);
                getImageHandler().handleImage((Image)img, imageElement,
                generatorCtx);
                imageElement.setAttributeNS(null, SVG_X_ATTRIBUTE,
                Integer.toString(x));
                imageElement.setAttributeNS(null, SVG_Y_ATTRIBUTE,
                Integer.toString(y));
                imageElement.setAttributeNS(null, SVG_WIDTH_ATTRIBUTE,
                Integer.toString(img.getWidth(null)));
                imageElement.setAttributeNS(null, SVG_HEIGHT_ATTRIBUTE,
                Integer.toString(img.getHeight(null)));
                imageElement.setAttributeNS(null, SVG_FILTER_ATTRIBUTE,
                filterDesc.getFilterValue());
                Element imageGroup = generatorCtx.domFactory.createElementNS(SVG_NAMESPACE_URI,
                SVG_G_TAG);
                imageGroup.appendChild(imageElement);

                    domGroupManager.addElement(imageGroup);
                }
                else{
                    //
                    // Could not convert to an equivalent SVG filter:
                    // filter now and draw resulting image
                    //
                    img = op.filter(img, null);
                    drawImage(img, x, y, null);
                }
            }
        }
        else{*/
    //
    // Input image is not sRGB non premultiplied.
    // Do not try conversion: apply filter and paint
    //
    img = op.filter(img, null);
    drawImage(img, x, y, null);
// }
}
Example 9
Project: freehep-ncolor-pdf-master  File: JAVAGraphics2D.java View source code
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    if (op instanceof AffineTransformOp) {
        out.print(vg() + ".drawImage(");
        out.indent();
        write(img);
        out.println(",");
        write((AffineTransformOp) op);
        out.println(",");
        out.println(x + ", " + y + ");");
        out.outdent();
    } else if (op instanceof ConvolveOp) {
        out.print(vg() + ".drawImage(");
        out.indent();
        write(img);
        out.println(",");
        write((ConvolveOp) op);
        out.println(",");
        out.println(x + ", " + y + ");");
        out.outdent();
    } else {
        out.println("System.err.println(\"" + getClass() + ": drawImage(BufferedImage, BufferedImageOp, int, int) not implemented.\");");
    }
}
Example 10
Project: freehep-vectorgraphics-master  File: JAVAGraphics2D.java View source code
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    if (op instanceof AffineTransformOp) {
        out.print(vg() + ".drawImage(");
        out.indent();
        write(img);
        out.println(",");
        write((AffineTransformOp) op);
        out.println(",");
        out.println(x + ", " + y + ");");
        out.outdent();
    } else if (op instanceof ConvolveOp) {
        out.print(vg() + ".drawImage(");
        out.indent();
        write(img);
        out.println(",");
        write((ConvolveOp) op);
        out.println(",");
        out.println(x + ", " + y + ");");
        out.outdent();
    } else {
        out.println("System.err.println(\"" + getClass() + ": drawImage(BufferedImage, BufferedImageOp, int, int) not implemented.\");");
    }
}
Example 11
Project: OpenAppEngine-master  File: ImagesService.java View source code
private Image resize(Image image, int width, int height) {
    Mode translationMode = Mode.AUTOMATIC;
    if (image.getWidth() < width && image.getHeight() < height) {
        return image;
    } else if (image.getWidth() < width) {
        translationMode = Mode.FIT_TO_HEIGHT;
    } else if (image.getHeight() < height) {
        translationMode = Mode.FIT_TO_WIDTH;
    } else {
        float wRatio = ((float) width / (float) image.getWidth());
        float hRatio = ((float) height / (float) image.getHeight());
        translationMode = wRatio < hRatio ? Mode.FIT_TO_WIDTH : Mode.FIT_TO_HEIGHT;
    }
    BufferedImage bufferedImage = Scalr.resize(image.getNativeImage(), translationMode, width, height, (BufferedImageOp) null);
    /*
		java.awt.Image scaledImage = image.getNativeImage().getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH);
		BufferedImage bufferedImage = new BufferedImage(width, height, image.getNativeImage().getType());
		bufferedImage.getGraphics().drawImage(scaledImage, 0, 0 , null);
		*/
    return new Image(bufferedImage, image.getFormat());
}
Example 12
Project: PSD-master  File: AbstractFilter.java View source code
protected static void exercise(final String[] args, final BufferedImageOp filter, final Color background) throws IOException {
    boolean original = false;
    for (String arg : args) {
        if (arg.startsWith("-")) {
            if (arg.equals("-o") || arg.equals("--original")) {
                original = true;
            }
            continue;
        }
        final File file = new File(arg);
        BufferedImage image = ImageIO.read(file);
        if (image.getWidth() > 640) {
            image = new ResampleOp(640, Math.round(image.getHeight() * (640f / image.getWidth())), null).filter(image, null);
        }
        if (!original) {
            filter.filter(image, image);
        }
        final Color bg = original ? Color.BLACK : background;
        final BufferedImage img = image;
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame(filter.getClass().getSimpleName().replace("Filter", "") + "Test: " + file.getName());
                frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    @Override
                    public void windowClosed(final WindowEvent e) {
                        Window[] windows = Window.getWindows();
                        if (windows == null || windows.length == 0) {
                            System.exit(0);
                        }
                    }
                });
                frame.getRootPane().getActionMap().put("window-close", new AbstractAction() {

                    public void actionPerformed(ActionEvent e) {
                        Window window = SwingUtilities.getWindowAncestor((Component) e.getSource());
                        window.setVisible(false);
                        window.dispose();
                    }
                });
                frame.getRootPane().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "window-close");
                JLabel label = new JLabel(new BufferedImageIcon(img));
                if (bg != null) {
                    label.setOpaque(true);
                    label.setBackground(bg);
                }
                label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
                JScrollPane scrollPane = new JScrollPane(label);
                scrollPane.setBorder(BorderFactory.createEmptyBorder());
                frame.add(scrollPane);
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }
}
Example 13
Project: TwelveMonkeys-master  File: AbstractFilter.java View source code
protected static void exercise(final String[] args, final BufferedImageOp filter, final Color background) throws IOException {
    boolean original = false;
    for (String arg : args) {
        if (arg.startsWith("-")) {
            if (arg.equals("-o") || arg.equals("--original")) {
                original = true;
            }
            continue;
        }
        final File file = new File(arg);
        BufferedImage image = ImageIO.read(file);
        if (image.getWidth() > 640) {
            image = new ResampleOp(640, Math.round(image.getHeight() * (640f / image.getWidth())), null).filter(image, null);
        }
        if (!original) {
            filter.filter(image, image);
        }
        final Color bg = original ? Color.BLACK : background;
        final BufferedImage img = image;
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame(filter.getClass().getSimpleName().replace("Filter", "") + "Test: " + file.getName());
                frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    @Override
                    public void windowClosed(final WindowEvent e) {
                        Window[] windows = Window.getWindows();
                        if (windows == null || windows.length == 0) {
                            System.exit(0);
                        }
                    }
                });
                frame.getRootPane().getActionMap().put("window-close", new AbstractAction() {

                    public void actionPerformed(ActionEvent e) {
                        Window window = SwingUtilities.getWindowAncestor((Component) e.getSource());
                        window.setVisible(false);
                        window.dispose();
                    }
                });
                frame.getRootPane().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "window-close");
                JLabel label = new JLabel(new BufferedImageIcon(img));
                if (bg != null) {
                    label.setOpaque(true);
                    label.setBackground(bg);
                }
                label.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
                JScrollPane scrollPane = new JScrollPane(label);
                scrollPane.setBorder(BorderFactory.createEmptyBorder());
                frame.add(scrollPane);
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }
}
Example 14
Project: CaliphEmir-master  File: ImageViewPanel.java View source code
public void setOp(BufferedImageOp op) {
    this.op = op;
    if (op != null)
        this.setPreferredSize(new Dimension(img.getHeight(null) + 2 * EMPTY_BORDER, img.getWidth(null) + 2 * EMPTY_BORDER));
    else
        this.setPreferredSize(new Dimension(img.getWidth(null) + 2 * EMPTY_BORDER, img.getHeight(null) + 2 * EMPTY_BORDER));
}
Example 15
Project: icepdf-master  File: BlurredImageReference.java View source code
public BufferedImage call() {
    BufferedImage image = null;
    long start = System.nanoTime();
    try {
        image = imageStream.getImage(graphicsState, resources);
        if (image.getWidth() > minWidth && image.getHeight() > minHeight) {
            BufferedImageOp op = new ConvolveOp(new Kernel(dimension, dimension, matrix));
            image = op.filter(image, null);
        }
    } catch (Throwable e) {
        logger.log(Level.WARNING, "Error loading image: " + imageStream.getPObjectReference() + " " + imageStream.toString(), e);
    }
    long end = System.nanoTime();
    notifyImagePageEvents((end - start));
    return image;
}
Example 16
Project: jdk7u-jdk-master  File: PathGraphics.java View source code
/**
     * Draws a BufferedImage that is filtered with a BufferedImageOp.
     * The rendering attributes applied include the clip, transform
     * and composite attributes.  This is equivalent to:
     * <pre>
     * img1 = op.filter(img, null);
     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
     * </pre>
     * @param op The filter to be applied to the image before drawing.
     * @param img The BufferedImage to be drawn.
     *            This method does nothing if <code>img</code> is null.
     * @param x,y The location in user space where the image should be drawn.
     * @see #transform
     * @see #setTransform
     * @see #setComposite
     * @see #clip
     * @see #setClip
     */
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    if (img == null) {
        return;
    }
    int srcWidth = img.getWidth(null);
    int srcHeight = img.getHeight(null);
    if (op != null) {
        img = op.filter(img, null);
    }
    if (srcWidth <= 0 || srcHeight <= 0) {
        return;
    } else {
        AffineTransform xform = new AffineTransform(1f, 0f, 0f, 1f, x, y);
        drawImageToPlatform(img, xform, null, 0, 0, srcWidth, srcHeight, false);
    }
}
Example 17
Project: LearningCommunity-master  File: CaptchaHandler.java View source code
public void init() {
    myCaptcha = new MyCaptcha();
    configurableCaptchaService = new ConfigurableCaptchaService();
    // 颜色创建工厂,使用一定范围内的�机色  
    colorFactory = new RandomColorFactory();
    configurableCaptchaService.setColorFactory(colorFactory);
    // �机字体生�器  
    fontFactory = new RandomFontFactory();
    fontFactory.setMaxSize(32);
    fontFactory.setMinSize(28);
    configurableCaptchaService.setFontFactory(fontFactory);
    // �机字符生�器,去除掉容易混淆的字�和数字,如o和0等  
    wordFactory = new RandomWordFactory();
    wordFactory.setCharacters("abcdefghkmnpqstwxyz23456789");
    wordFactory.setMaxLength(5);
    wordFactory.setMinLength(4);
    configurableCaptchaService.setWordFactory(wordFactory);
    // 自定义验��图片背景  
    CustomBackgroundFactory backgroundFactory = new CustomBackgroundFactory();
    configurableCaptchaService.setBackgroundFactory(backgroundFactory);
    // 图片滤镜设置  
    ConfigurableFilterFactory filterFactory = new ConfigurableFilterFactory();
    List<BufferedImageOp> filters = new ArrayList<BufferedImageOp>();
    WobbleImageOp wobbleImageOp = new WobbleImageOp();
    wobbleImageOp.setEdgeMode(AbstractImageOp.EDGE_MIRROR);
    wobbleImageOp.setxAmplitude(2.0);
    wobbleImageOp.setyAmplitude(1.0);
    filters.add(wobbleImageOp);
    filterFactory.setFilters(filters);
    configurableCaptchaService.setFilterFactory(filterFactory);
    // 文字渲染器设置  
    textRenderer = new BestFitTextRenderer();
    textRenderer.setBottomMargin(3);
    textRenderer.setTopMargin(3);
    configurableCaptchaService.setTextRenderer(textRenderer);
    // 验��图片的大�  
    configurableCaptchaService.setWidth(80);
    configurableCaptchaService.setHeight(35);
}
Example 18
Project: openjdk-master  File: PathGraphics.java View source code
/**
     * Draws a BufferedImage that is filtered with a BufferedImageOp.
     * The rendering attributes applied include the clip, transform
     * and composite attributes.  This is equivalent to:
     * <pre>
     * img1 = op.filter(img, null);
     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
     * </pre>
     * @param op The filter to be applied to the image before drawing.
     * @param img The BufferedImage to be drawn.
     *            This method does nothing if {@code img} is null.
     * @param x,y The location in user space where the image should be drawn.
     * @see #transform
     * @see #setTransform
     * @see #setComposite
     * @see #clip
     * @see #setClip
     */
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    if (img == null) {
        return;
    }
    int srcWidth = img.getWidth(null);
    int srcHeight = img.getHeight(null);
    if (op != null) {
        img = op.filter(img, null);
    }
    if (srcWidth <= 0 || srcHeight <= 0) {
        return;
    } else {
        AffineTransform xform = new AffineTransform(1f, 0f, 0f, 1f, x, y);
        drawImageToPlatform(img, xform, null, 0, 0, srcWidth, srcHeight, false);
    }
}
Example 19
Project: openjdk8-jdk-master  File: PathGraphics.java View source code
/**
     * Draws a BufferedImage that is filtered with a BufferedImageOp.
     * The rendering attributes applied include the clip, transform
     * and composite attributes.  This is equivalent to:
     * <pre>
     * img1 = op.filter(img, null);
     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
     * </pre>
     * @param op The filter to be applied to the image before drawing.
     * @param img The BufferedImage to be drawn.
     *            This method does nothing if <code>img</code> is null.
     * @param x,y The location in user space where the image should be drawn.
     * @see #transform
     * @see #setTransform
     * @see #setComposite
     * @see #clip
     * @see #setClip
     */
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    if (img == null) {
        return;
    }
    int srcWidth = img.getWidth(null);
    int srcHeight = img.getHeight(null);
    if (op != null) {
        img = op.filter(img, null);
    }
    if (srcWidth <= 0 || srcHeight <= 0) {
        return;
    } else {
        AffineTransform xform = new AffineTransform(1f, 0f, 0f, 1f, x, y);
        drawImageToPlatform(img, xform, null, 0, 0, srcWidth, srcHeight, false);
    }
}
Example 20
Project: Pixelitor-master  File: AbstractPainter.java View source code
/**
     * <p>A convenience method for specifying the filters to use based on
     * BufferedImageOps. These will each be individually wrapped by an ImageFilter
     * and then setFilters(Effect... filters) will be called with the resulting
     * array</p>
     *
     * @param effects the BufferedImageOps to wrap as filters
     */
public void setFilters(BufferedImageOp... effects) {
    if (effects == null)
        effects = new BufferedImageOp[0];
    BufferedImageOp[] old = getFilters();
    this.filters = new BufferedImageOp[effects == null ? 0 : effects.length];
    System.arraycopy(effects, 0, this.filters, 0, this.filters.length);
    setDirty(true);
    firePropertyChange("filters", old, getFilters());
}
Example 21
Project: ae-awt-master  File: SunGraphics2D.java View source code
public void drawImage(BufferedImage bImg, BufferedImageOp op, int x, int y) {
    if (bImg == null) {
        return;
    }
    try {
        imagepipe.transformImage(this, bImg, op, x, y);
    } catch (InvalidPipeException e) {
        revalidateAll();
        try {
            imagepipe.transformImage(this, bImg, op, x, y);
        } catch (InvalidPipeException e2) {
        }
    } finally {
        surfaceData.markDirty();
    }
}
Example 22
Project: com.idega.graphics-master  File: ImageResizerImpl.java View source code
private byte[] getScaledImage(int newWidth, int newHeight, int minSize, InputStream streamToImage, String imageType, Integer scaleIfBiggerThan) throws IOException {
    if (streamToImage == null) {
        getLogger().warning("Stream to image is not provided!");
        return null;
    }
    int originalWidth = -1, originalHeight = -1;
    long start = System.currentTimeMillis();
    ByteArrayOutputStream output = null;
    try {
        BufferedImage image = ImageIO.read(streamToImage);
        originalHeight = image.getHeight();
        boolean scale = true;
        if (scaleIfBiggerThan != null && originalHeight <= scaleIfBiggerThan) {
            scale = false;
        }
        BufferedImage scaled = null;
        if (scale) {
            if (newWidth < 0 && newHeight < 0 && minSize > 0) {
                originalWidth = image.getWidth();
                double ratio = minSize * 1.0 / originalWidth;
                newHeight = Double.valueOf(originalHeight * ratio).intValue();
                if (newHeight < minSize) {
                    ratio = minSize * 1.0 / originalHeight;
                }
                newHeight = Double.valueOf(originalHeight * ratio).intValue();
                newWidth = Double.valueOf(originalWidth * ratio).intValue();
            }
            IWMainApplicationSettings settings = IWMainApplication.getDefaultIWMainApplication().getSettings();
            List<BufferedImageOp> options = new ArrayList<BufferedImageOp>();
            if (settings.getBoolean("graphics.resizer_antialias", Boolean.TRUE)) {
                options.add(Scalr.OP_ANTIALIAS);
            }
            if (settings.getBoolean("graphics.resizer_brighter", Boolean.TRUE)) {
                options.add(Scalr.OP_BRIGHTER);
            }
            Method method = Method.valueOf(settings.getProperty("graphics.resizer_method", Method.SPEED.name()));
            Mode resizeMode = Mode.valueOf(settings.getProperty("graphics.resizer_mode", Mode.AUTOMATIC.name()));
            if (ListUtil.isEmpty(options)) {
                scaled = Scalr.resize(image, method, resizeMode, newWidth, newHeight);
            } else {
                scaled = Scalr.resize(image, method, resizeMode, newWidth, newHeight, ArrayUtil.convertListToArray(options));
            }
        } else {
            scaled = image;
        }
        output = new ByteArrayOutputStream();
        ImageIO.write(scaled, imageType, output);
        return output.toByteArray();
    } finally {
        IOUtil.close(streamToImage);
        IOUtil.close(output);
        long duration = System.currentTimeMillis() - start;
        if (duration > 300) {
            getLogger().info("It took " + duration + " ms to scale image from " + originalWidth + "x" + originalHeight + " to " + newWidth + "x" + newHeight);
        }
    }
}
Example 23
Project: earthsci-master  File: FilterTransformerDelegate.java View source code
@Override
public IDelegate fromDefinition(String definition, Element layerElement, AVList params) {
    if (definition.toLowerCase().equals(DEFINITION_STRING.toLowerCase())) {
        List<BufferedImageOp> filters = new ArrayList<BufferedImageOp>();
        XPath xpath = XMLUtil.makeXPath();
        Element[] filterElements = XMLUtil.getElements(layerElement, "Filters/Filter", xpath);
        if (filterElements != null) {
            for (Element filterElement : filterElements) {
                String name = XMLUtil.getText(filterElement, "@name", xpath);
                try {
                    Class<?> filterClass = null;
                    try {
                        //first try class name with the local .filter package prefix
                        filterClass = Class.forName(TransparentMinimumFilter.class.getPackage().getName() + "." + name);
                    } catch (ClassNotFoundException e) {
                    }
                    if (filterClass == null) {
                        try {
                            //next try class name with the com.jhlabs.image package prefix
                            filterClass = Class.forName(AbstractBufferedImageOp.class.getPackage().getName() + "." + name);
                        } catch (ClassNotFoundException e) {
                        }
                    }
                    if (filterClass == null) {
                        try {
                            //if not found, simply try the name as the full class name
                            filterClass = Class.forName(name);
                        } catch (ClassNotFoundException e) {
                            throw new Exception("Filter not found: " + name, e);
                        }
                    }
                    Object filterObject = filterClass.newInstance();
                    if (filterObject instanceof BufferedImageOp) {
                        BufferedImageOp filter = (BufferedImageOp) filterObject;
                        filters.add(filter);
                        PropertySetter setter = new PropertySetter();
                        StyleAndAttributeFactory.addProperties(filterElement, xpath, setter);
                        setter.setPropertiesFromAttributes(null, null, filter);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return new FilterTransformerDelegate(filters);
    }
    return null;
}
Example 24
Project: ikvm-openjdk-master  File: PathGraphics.java View source code
/**
     * Draws a BufferedImage that is filtered with a BufferedImageOp.
     * The rendering attributes applied include the clip, transform
     * and composite attributes.  This is equivalent to:
     * <pre>
     * img1 = op.filter(img, null);
     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
     * </pre>
     * @param op The filter to be applied to the image before drawing.
     * @param img The BufferedImage to be drawn.
     *            This method does nothing if <code>img</code> is null.
     * @param x,y The location in user space where the image should be drawn.
     * @see #transform
     * @see #setTransform
     * @see #setComposite
     * @see #clip
     * @see #setClip
     */
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    if (img == null) {
        return;
    }
    int srcWidth = img.getWidth(null);
    int srcHeight = img.getHeight(null);
    if (op != null) {
        img = op.filter(img, null);
    }
    if (srcWidth <= 0 || srcHeight <= 0) {
        return;
    } else {
        AffineTransform xform = new AffineTransform(1f, 0f, 0f, 1f, x, y);
        drawImageToPlatform(img, xform, null, 0, 0, srcWidth, srcHeight, false);
    }
}
Example 25
Project: javamelody-master  File: MainFrame.java View source code
/**
	 * Floute ou défloute le contentPane de la frame principale.
	 * @param blur boolean
	 */
public void setBlurContentPane(boolean blur) {
    final JXLayer jxLayer = (JXLayer) getContentPane();
    if (blur && jxLayer.getBufferedImageOp() instanceof FastBlurFilter || !blur && !(jxLayer.getBufferedImageOp() instanceof FastBlurFilter)) {
        return;
    }
    final BufferedImageOp bio = new FastBlurFilter(1);
    jxLayer.setBufferedImageOp(blur ? bio : null);
}
Example 26
Project: javamelody-mirror-backup-master  File: MainFrame.java View source code
/**
	 * Floute ou défloute le contentPane de la frame principale.
	 * @param blur boolean
	 */
public void setBlurContentPane(boolean blur) {
    final JXLayer jxLayer = (JXLayer) getContentPane();
    if (blur && jxLayer.getBufferedImageOp() instanceof FastBlurFilter || !blur && !(jxLayer.getBufferedImageOp() instanceof FastBlurFilter)) {
        return;
    }
    final BufferedImageOp bio = new FastBlurFilter(1);
    jxLayer.setBufferedImageOp(blur ? bio : null);
}
Example 27
Project: ManagedRuntimeInitiative-master  File: PathGraphics.java View source code
/**
     * Draws a BufferedImage that is filtered with a BufferedImageOp.
     * The rendering attributes applied include the clip, transform
     * and composite attributes.  This is equivalent to:
     * <pre>
     * img1 = op.filter(img, null);
     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
     * </pre>
     * @param op The filter to be applied to the image before drawing.
     * @param img The BufferedImage to be drawn.
     *            This method does nothing if <code>img</code> is null.
     * @param x,y The location in user space where the image should be drawn.
     * @see #transform
     * @see #setTransform
     * @see #setComposite
     * @see #clip
     * @see #setClip
     */
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    if (img == null) {
        return;
    }
    int srcWidth = img.getWidth(null);
    int srcHeight = img.getHeight(null);
    if (op != null) {
        img = op.filter(img, null);
    }
    if (srcWidth <= 0 || srcHeight <= 0) {
        return;
    } else {
        AffineTransform xform = new AffineTransform(1f, 0f, 0f, 1f, x, y);
        drawImageToPlatform(img, xform, null, 0, 0, srcWidth, srcHeight, false);
    }
}
Example 28
Project: SnippingToolPlusPlus-master  File: ImageUtilities.java View source code
public static Image simpleBlur(Image img) {
    Image sourceImage = img;
    // Create a buffered image from the source image with a format that's compatible with the screen
    GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice graphicsDevice = graphicsEnvironment.getDefaultScreenDevice();
    GraphicsConfiguration graphicsConfiguration = graphicsDevice.getDefaultConfiguration();
    // If the source image has no alpha info use Transparency.OPAQUE instead
    image = graphicsConfiguration.createCompatibleImage(sourceImage.getWidth(null), sourceImage.getHeight(null), Transparency.BITMASK);
    // Copy image to buffered image
    Graphics graphics = ((BufferedImage) image).createGraphics();
    // Paint the image onto the buffered image
    graphics.drawImage(sourceImage, 0, 0, null);
    graphics.dispose();
    // A 3x3 kernel that blurs an image
    Kernel kernel = new Kernel(3, 3, new float[] { 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f });
    BufferedImageOp op = new ConvolveOp(kernel);
    for (int i = 0; i < 2; i++) {
        image = op.filter((BufferedImage) image, null);
    }
    return image;
}
Example 29
Project: classlib6-master  File: PathGraphics.java View source code
/**
     * Draws a BufferedImage that is filtered with a BufferedImageOp.
     * The rendering attributes applied include the clip, transform
     * and composite attributes.  This is equivalent to:
     * <pre>
     * img1 = op.filter(img, null);
     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
     * </pre>
     * @param op The filter to be applied to the image before drawing.
     * @param img The BufferedImage to be drawn.
     *            This method does nothing if <code>img</code> is null.
     * @param x,y The location in user space where the image should be drawn.
     * @see #transform
     * @see #setTransform
     * @see #setComposite
     * @see #clip
     * @see #setClip
     */
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    if (img == null) {
        return;
    }
    int srcWidth = img.getWidth(null);
    int srcHeight = img.getHeight(null);
    if (op != null) {
        img = op.filter(img, null);
    }
    if (srcWidth <= 0 || srcHeight <= 0) {
        return;
    } else {
        AffineTransform xform = new AffineTransform(1f, 0f, 0f, 1f, x, y);
        drawImageToPlatform(img, xform, null, 0, 0, srcWidth, srcHeight, false);
    }
}
Example 30
Project: com.opendoorlogistics-master  File: AbstractPainter.java View source code
/**
     * <p>A convenience method for specifying the filters to use based on
     * BufferedImageOps. These will each be individually wrapped by an ImageFilter
     * and then setFilters(Effect... filters) will be called with the resulting
     * array</p>
     * 
     * 
     * @param effects the BufferedImageOps to wrap as filters
     */
public void setFilters(BufferedImageOp... effects) {
    if (effects == null)
        effects = new BufferedImageOp[0];
    BufferedImageOp[] old = getFilters();
    this.filters = new BufferedImageOp[effects.length];
    System.arraycopy(effects, 0, this.filters, 0, this.filters.length);
    setDirty(true);
    firePropertyChange("filters", old, getFilters());
}
Example 31
Project: HearthStats.net-Uploader-master  File: OcrBase.java View source code
/**
     * Filters the image to make it easier to OCR, such as by turning it greyscale and increasing the contrast.
     *
     * @param image A cropped image
     * @param iteration The iteration number, zero-based
     * @return
     * @throws OcrException
     */
protected BufferedImage filter(BufferedImage image, int iteration) throws OcrException {
    int width = image.getWidth();
    int height = image.getHeight();
    int bigWidth = width * 3;
    int bigHeight = height * 3;
    // to gray scale
    BufferedImage grayscale = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
    BufferedImageOp grayscaleConv = new ColorConvertOp(image.getColorModel().getColorSpace(), grayscale.getColorModel().getColorSpace(), null);
    grayscaleConv.filter(image, grayscale);
    // blow it up for ocr
    BufferedImage newImage = new BufferedImage(bigWidth, bigHeight, BufferedImage.TYPE_INT_RGB);
    Graphics g = newImage.createGraphics();
    g.drawImage(grayscale, 0, 0, bigWidth, bigHeight, null);
    g.dispose();
    // invert image
    for (int x = 0; x < bigWidth; x++) {
        for (int y = 0; y < bigHeight; y++) {
            int rgba = newImage.getRGB(x, y);
            Color col = new Color(rgba, true);
            col = new Color(255 - col.getRed(), 255 - col.getGreen(), 255 - col.getBlue());
            newImage.setRGB(x, y, col.getRGB());
        }
    }
    // increase contrast
    try {
        RescaleOp rescaleOp = new RescaleOp(1.8f, -30, null);
        // Source and destination are the same.
        rescaleOp.filter(newImage, newImage);
    } catch (Exception e) {
        throw new OcrException("Error rescaling OCR image", e);
    }
    return newImage;
}
Example 32
Project: jif-master  File: ImageDicer.java View source code
/**
   * createThresholdOp() uses a LookupOp to simulate a
   * thresholding operation.
  **/
private BufferedImageOp createThresholdOp(int threshold, int minimum, int maximum) {
    short[] thresholdArray = new short[256];
    for (int i = 0; i < 256; i++) {
        if (i < threshold)
            thresholdArray[i] = (short) minimum;
        else
            thresholdArray[i] = (short) maximum;
    }
    return new LookupOp(new ShortLookupTable(0, thresholdArray), null);
}
Example 33
Project: mobilitytestbed-master  File: HeatMapKmlItem.java View source code
private BufferedImage filterImage(BufferedImage image) {
    double maxAlpha = getMaxAlpha(image);
    //		logger.debug(maxAlpha);
    ColorMap colorMap = new ColorMap(pointAlpha - 1, maxAlpha * 0.9, ColorMap.HUE_BLUE_TO_RED);
    BufferedImage im = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
    // blur image
    int side = FIRST_BLUR_SIZE;
    float[] blurMatrix = createBlurMatrix(side, side);
    Kernel kernel = new Kernel(side, side, blurMatrix);
    BufferedImageOp op = new ConvolveOp(kernel);
    im = op.filter(image, null);
    // change colors
    for (int w = 0; w < im.getWidth(); w++) {
        for (int h = 0; h < im.getHeight(); h++) {
            int rgb = im.getRGB(w, h);
            if (rgb == 0) {
                im.setRGB(w, h, rgb);
            } else {
                int alpha = new Color(rgb, true).getAlpha();
                if (alpha > 0) {
                //						logger.debug(alpha);
                }
                im.setRGB(w, h, colorMap.getColor(alpha).getRGB());
            }
        }
    }
    // blur again
    side = SECOND_BLUR_SIZE;
    blurMatrix = createBlurMatrix(side, side);
    kernel = new Kernel(side, side, blurMatrix);
    op = new ConvolveOp(kernel);
    im = op.filter(im, null);
    // reverse vertically
    AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
    tx.translate(0, -im.getHeight(null));
    AffineTransformOp opp = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    im = opp.filter(im, null);
    return im;
}
Example 34
Project: swingx-master  File: PainterDemo.java View source code
/**
     * Create and return model for filter selection combobox.
     * 
     * @return
     */
private ComboBoxModel createFilterList() {
    DefaultComboBoxModel model = new DefaultComboBoxModel();
    model.addElement(new DisplayInfo<BufferedImageOp>("- none - ", null));
    model.addElement(new DisplayInfo<BufferedImageOp>(new AverageFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new BlockFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new BlurFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new BorderFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new BoxBlurFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new BumpFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new ChromeFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new ContrastFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new CrystallizeFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new DespeckleFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new DiffuseFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new DiffusionFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new DilateFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new DisplaceFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new DitherFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new EdgeFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new EmbossFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new EqualizeFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new ErodeFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new FlareFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new GainFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new GammaFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new GaussianFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new GlintFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new GlowFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new GrayFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new InvertFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new InvertAlphaFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new LensBlurFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new LevelsFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new LifeFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new MarbleFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new MarbleTexFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new MedianFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new MinimumFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new MirrorFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new MotionBlurFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new NoiseFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new OilFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new OpacityFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new OutlineFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new PointillizeFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new PosterizeFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new QuantizeFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new RaysFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new ReduceNoiseFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new RippleFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new ShadowFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new SharpenFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new SkeletonFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new SmearFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new SolarizeFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new SparkleFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new SphereFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new SwimFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new ThresholdFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new TwirlFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new UnsharpFilter()));
    model.addElement(new DisplayInfo<BufferedImageOp>(new WaterFilter()));
    return model;
}
Example 35
Project: posClient-master  File: AbstractBlackBoxTestCase.java View source code
protected static BufferedImage rotateImage(BufferedImage original, float degrees) {
    if (degrees == 0.0f) {
        return original;
    } else {
        double radians = Math.toRadians(degrees);
        // Transform simply to find out the new bounding box (don't actually run the image through it)
        AffineTransform at = new AffineTransform();
        at.rotate(radians, original.getWidth() / 2.0, original.getHeight() / 2.0);
        BufferedImageOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
        Rectangle2D r = op.getBounds2D(original);
        int width = (int) Math.ceil(r.getWidth());
        int height = (int) Math.ceil(r.getHeight());
        // Real transform, now that we know the size of the new image and how to translate after we rotate
        // to keep it centered
        at = new AffineTransform();
        at.rotate(radians, width / 2.0, height / 2.0);
        at.translate((width - original.getWidth()) / 2.0, (height - original.getHeight()) / 2.0);
        op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
        return op.filter(original, null);
    }
}
Example 36
Project: powerpaint-master  File: TileSurfaceGraphics.java View source code
@Override
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    int width = img.getWidth();
    int height = img.getHeight();
    int area = width * height;
    AffineTransform tx = modelGraphics.getTransform();
    Shape clip = modelGraphics.getClip();
    if ((op == null) && (area < 10000) && (tx == null || tx.isIdentity()) && (clip == null || clip.contains(x, y, width, height))) {
        BufferedImage dst = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        int[] dstRGB = new int[area];
        ts.getRGB(x, y, width, height, dstRGB, 0, width);
        dst.setRGB(0, 0, width, height, dstRGB, 0, width);
        CompositeContext cc = getComposite().createContext(img.getColorModel(), dst.getColorModel(), getRenderingHints());
        cc.compose(img.getData(), dst.getData(), dst.getRaster());
        dst.getRGB(0, 0, width, height, dstRGB, 0, width);
        ts.setRGB(x, y, width, height, dstRGB, 0, width);
        return;
    }
    Rectangle s = (op == null) ? new Rectangle(0, 0, width, height) : op.getBounds2D(img).getBounds();
    s.x += x;
    s.y += y;
    Collection<Tile> tt = getTilesForShape(s);
    for (Tile t : tt) {
        Graphics2D g = createGraphics(t);
        g.drawImage(img, op, x, y);
        g.dispose();
    }
}
Example 37
Project: QRCode-APG-master  File: AbstractBlackBoxTestCase.java View source code
protected static BufferedImage rotateImage(BufferedImage original, float degrees) {
    if (degrees == 0.0f) {
        return original;
    } else {
        double radians = Math.toRadians(degrees);
        // Transform simply to find out the new bounding box (don't actually run the image through it)
        AffineTransform at = new AffineTransform();
        at.rotate(radians, original.getWidth() / 2.0, original.getHeight() / 2.0);
        BufferedImageOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
        Rectangle2D r = op.getBounds2D(original);
        int width = (int) Math.ceil(r.getWidth());
        int height = (int) Math.ceil(r.getHeight());
        // Real transform, now that we know the size of the new image and how to translate after we rotate
        // to keep it centered
        at = new AffineTransform();
        at.rotate(radians, width / 2.0, height / 2.0);
        at.translate(((width - original.getWidth()) / 2.0), ((height - original.getHeight()) / 2.0));
        op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
        return op.filter(original, null);
    }
}
Example 38
Project: shopizer-v1.1.5-master  File: ProductImageUtil.java View source code
public BufferedImage blurImage(BufferedImage image) {
    float ninth = 1.0f / 9.0f;
    float[] blurKernel = { ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth };
    Map<Key, Object> map = new HashMap<Key, Object>();
    map.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    map.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    map.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    RenderingHints hints = new RenderingHints(map);
    BufferedImageOp op = new ConvolveOp(new Kernel(3, 3, blurKernel), ConvolveOp.EDGE_NO_OP, hints);
    return op.filter(image, null);
}
Example 39
Project: Tutorial_ZXingConAndroid-master  File: AbstractBlackBoxTestCase.java View source code
protected static BufferedImage rotateImage(BufferedImage original, float degrees) {
    if (degrees == 0.0f) {
        return original;
    } else {
        double radians = Math.toRadians(degrees);
        // Transform simply to find out the new bounding box (don't actually run the image through it)
        AffineTransform at = new AffineTransform();
        at.rotate(radians, original.getWidth() / 2.0, original.getHeight() / 2.0);
        BufferedImageOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
        Rectangle2D r = op.getBounds2D(original);
        int width = (int) Math.ceil(r.getWidth());
        int height = (int) Math.ceil(r.getHeight());
        // Real transform, now that we know the size of the new image and how to translate after we rotate
        // to keep it centered
        at = new AffineTransform();
        at.rotate(radians, width / 2.0, height / 2.0);
        at.translate((width - original.getWidth()) / 2.0, (height - original.getHeight()) / 2.0);
        op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
        return op.filter(original, null);
    }
}
Example 40
Project: zxing-iphone-master  File: AbstractBlackBoxTestCase.java View source code
protected static BufferedImage rotateImage(BufferedImage original, float degrees) {
    if (degrees == 0.0f) {
        return original;
    } else {
        AffineTransform at = new AffineTransform();
        at.rotate(Math.toRadians(degrees), original.getWidth() / 2.0, original.getHeight() / 2.0);
        BufferedImageOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
        return op.filter(original, null);
    }
}
Example 41
Project: eu3view-master  File: MapPanel.java View source code
private void rescaleMap() {
    if (scaledMapImage != null) {
        scaledMapImage.flush();
        scaledMapImage = null;
    }
    scaledMapImage = new BufferedImage((int) Math.ceil(mapImage.getWidth() * scaleFactor), (int) Math.ceil(mapImage.getHeight() * scaleFactor), mapImage.getType());
    final BufferedImageOp transform;
    if (new File(Main.filenameResolver.resolveFilename("common/faction.txt")).exists()) {
        // DW
        transform = new AffineTransformOp(new AffineTransform(scaleFactor, 0.0, 0.0, scaleFactor, 0.0, -scaledMapImage.getHeight()), scalingHints);
    } else {
        transform = new AffineTransformOp(new AffineTransform(scaleFactor, 0.0, 0.0, -scaleFactor, 0.0, 0.0), scalingHints);
    }
    scaledMapImage.createGraphics().drawImage(mapImage, transform, 0, scaledMapImage.getHeight());
}
Example 42
Project: medsavant-master  File: Dashboard.java View source code
public BufferedImage createBlurredImage(BufferedImage sourceImage) {
    // Create a buffered image from the source image with a format that's compatible with the screen
    GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice graphicsDevice = graphicsEnvironment.getDefaultScreenDevice();
    GraphicsConfiguration graphicsConfiguration = graphicsDevice.getDefaultConfiguration();
    // If the source image has no alpha info use Transparency.OPAQUE instead
    BufferedImage image = graphicsConfiguration.createCompatibleImage(sourceImage.getWidth(null), sourceImage.getHeight(null), Transparency.BITMASK);
    // Copy image to buffered image
    Graphics graphics = image.createGraphics();
    // Paint the image onto the buffered image
    graphics.drawImage(sourceImage, 0, 0, null);
    graphics.dispose();
    float[] matrix = { 1 / 16f, 1 / 8f, 1 / 16f, 1 / 8f, 1 / 4f, 1 / 8f, 1 / 16f, 1 / 8f, 1 / 16f };
    BufferedImageOp op = new ConvolveOp(new Kernel(3, 3, matrix));
    return op.filter(image, null);
}
Example 43
Project: Scute-master  File: JXImageView.java View source code
public void actionPerformed(ActionEvent evt) {
    Image img = getImage();
    BufferedImage src = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    BufferedImage dst = new BufferedImage(img.getHeight(null), img.getWidth(null), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) src.getGraphics();
    try {
        // smooth scaling
        g.drawImage(img, 0, 0, null);
    } finally {
        g.dispose();
    }
    AffineTransform trans = AffineTransform.getRotateInstance(Math.PI / 2, 0, 0);
    trans.translate(0, -src.getHeight());
    BufferedImageOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    op.filter(src, dst);
    setImage(dst);
}
Example 44
Project: SikuliX-2014-master  File: JXImageView.java View source code
@Override
public void actionPerformed(ActionEvent evt) {
    Image img = getImage();
    BufferedImage src = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    BufferedImage dst = new BufferedImage(img.getHeight(null), img.getWidth(null), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) src.getGraphics();
    try {
        // smooth scaling
        g.drawImage(img, 0, 0, null);
    } finally {
        g.dispose();
    }
    AffineTransform trans = AffineTransform.getRotateInstance(Math.PI / 2, 0, 0);
    trans.translate(0, -src.getHeight());
    BufferedImageOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    op.filter(src, dst);
    setImage(dst);
}
Example 45
Project: stripes-prototyping-master  File: AbstractBlackBoxTestCase.java View source code
protected static BufferedImage rotateImage(BufferedImage original, float degrees) {
    if (degrees == 0.0f) {
        return original;
    }
    switch(original.getType()) {
        case BufferedImage.TYPE_BYTE_INDEXED:
        case BufferedImage.TYPE_BYTE_BINARY:
            BufferedImage argb = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = argb.createGraphics();
            g.drawImage(original, 0, 0, null);
            g.dispose();
            original = argb;
            break;
        default:
            // nothing
            break;
    }
    double radians = Math.toRadians(degrees);
    // Transform simply to find out the new bounding box (don't actually run the image through it)
    AffineTransform at = new AffineTransform();
    at.rotate(radians, original.getWidth() / 2.0, original.getHeight() / 2.0);
    BufferedImageOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
    Rectangle2D r = op.getBounds2D(original);
    int width = (int) Math.ceil(r.getWidth());
    int height = (int) Math.ceil(r.getHeight());
    // Real transform, now that we know the size of the new image and how to translate after we rotate
    // to keep it centered
    at = new AffineTransform();
    at.rotate(radians, width / 2.0, height / 2.0);
    at.translate((width - original.getWidth()) / 2.0, (height - original.getHeight()) / 2.0);
    op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
    return op.filter(original, new BufferedImage(width, height, original.getType()));
}
Example 46
Project: Zxing-master  File: AbstractBlackBoxTestCase.java View source code
protected static BufferedImage rotateImage(BufferedImage original, float degrees) {
    if (degrees == 0.0f) {
        return original;
    }
    switch(original.getType()) {
        case BufferedImage.TYPE_BYTE_INDEXED:
        case BufferedImage.TYPE_BYTE_BINARY:
            BufferedImage argb = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics g = argb.createGraphics();
            g.drawImage(original, 0, 0, null);
            g.dispose();
            original = argb;
            break;
    }
    double radians = Math.toRadians(degrees);
    // Transform simply to find out the new bounding box (don't actually run the image through it)
    AffineTransform at = new AffineTransform();
    at.rotate(radians, original.getWidth() / 2.0, original.getHeight() / 2.0);
    BufferedImageOp op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
    RectangularShape r = op.getBounds2D(original);
    int width = (int) Math.ceil(r.getWidth());
    int height = (int) Math.ceil(r.getHeight());
    // Real transform, now that we know the size of the new image and how to translate after we rotate
    // to keep it centered
    at = new AffineTransform();
    at.rotate(radians, width / 2.0, height / 2.0);
    at.translate((width - original.getWidth()) / 2.0, (height - original.getHeight()) / 2.0);
    op = new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC);
    return op.filter(original, new BufferedImage(width, height, original.getType()));
}
Example 47
Project: jeboorker-master  File: ImageUtils.java View source code
/**
	 * Inverts the colors of the given image.
	 * @param src The image to be invert.
	 * @return The inverted image.
	 */
public static BufferedImage invertImage(final BufferedImage src) {
    final int w = src.getWidth();
    final int h = src.getHeight();
    final BufferedImage dst = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    final BufferedImageOp invertOp = new LookupOp(new ShortLookupTable(0, invertTable), null);
    if (src.getType() == BufferedImage.TYPE_BYTE_INDEXED || src.getType() == 12) {
        BufferedImage newSrc = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        newSrc.getGraphics().drawImage(src, 0, 0, null);
        return invertOp.filter(newSrc, dst);
    } else {
        return invertOp.filter(src, dst);
    }
}
Example 48
Project: JMaNGOS-master  File: FontTT.java View source code
/*
     * Create a standard Java2D bufferedimage for the font outline to later be
     * converted into a
     * texture
     */
private BufferedImage getOutlineFontImage(final char ch) {
    Font tempfont;
    tempfont = this.font.deriveFont((float) this.fontsize);
    // Create a temporary image to extract font size
    final BufferedImage tempfontImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g = (Graphics2D) tempfontImage.getGraphics();
    // // Add AntiAliasing /////
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // /////////////////////////
    g.setFont(tempfont);
    final FontMetrics fm = g.getFontMetrics();
    int charwidth = fm.charWidth(ch);
    if (charwidth <= 0) {
        charwidth = 1;
    }
    int charheight = fm.getHeight();
    if (charheight <= 0) {
        charheight = this.fontsize;
    }
    // Create another image for texture creation
    final int ot = (int) (this.fontsize / 24f);
    BufferedImage fontImage;
    fontImage = new BufferedImage(charwidth + (4 * ot), charheight + (4 * ot), BufferedImage.TYPE_INT_ARGB);
    final Graphics2D gt = (Graphics2D) fontImage.getGraphics();
    // // Add AntiAliasing /////
    gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // /////////////////////////
    gt.setFont(tempfont);
    // // Uncomment these to fill in the texture with a background color
    // // (used for debugging)
    // gt.setColor(Color.RED);
    // gt.fillRect(0, 0, charwidth, fontsize);
    // // Create Outline by painting the character in multiple positions and
    // blurring it
    gt.setColor(Color.WHITE);
    final int charx = -fm.getLeading() + (2 * ot);
    final int chary = 2 * ot;
    gt.drawString(String.valueOf(ch), (charx) + ot, (chary) + fm.getAscent());
    gt.drawString(String.valueOf(ch), (charx) - ot, (chary) + fm.getAscent());
    gt.drawString(String.valueOf(ch), (charx), (chary) + ot + fm.getAscent());
    gt.drawString(String.valueOf(ch), (charx), ((chary) - ot) + fm.getAscent());
    gt.drawString(String.valueOf(ch), (charx) + ot, (chary) + ot + fm.getAscent());
    gt.drawString(String.valueOf(ch), (charx) + ot, ((chary) - ot) + fm.getAscent());
    gt.drawString(String.valueOf(ch), (charx) - ot, (chary) + ot + fm.getAscent());
    gt.drawString(String.valueOf(ch), (charx) - ot, ((chary) - ot) + fm.getAscent());
    final float ninth = 1.0f / 9.0f;
    final float[] blurKernel = { ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth };
    final BufferedImageOp blur = new ConvolveOp(new Kernel(3, 3, blurKernel));
    final BufferedImage returnimage = blur.filter(fontImage, null);
    return returnimage;
}
Example 49
Project: jpexs-decompiler-master  File: Filtering.java View source code
public static SerializableImage convolution(SerializableImage src, float[] matrix, int w, int h) {
    BufferedImage dst = new BufferedImage(src.getWidth(), src.getHeight(), src.getType());
    BufferedImageOp op = new ConvolveOp(new Kernel(w, h, matrix), ConvolveOp.EDGE_ZERO_FILL, new RenderingHints(null));
    op.filter(src.getBufferedImage(), dst);
    return new SerializableImage(dst);
}
Example 50
Project: jxmapviewer2-master  File: AbstractPainter.java View source code
/**
     * <p>A convenience method for specifying the filters to use based on
     * BufferedImageOps. These will each be individually wrapped by an ImageFilter
     * and then setFilters(Effect... filters) will be called with the resulting
     * array</p>
     * 
     * 
     * @param effects the BufferedImageOps to wrap as filters
     */
public void setFilters(BufferedImageOp... effects) {
    if (effects == null)
        effects = new BufferedImageOp[0];
    BufferedImageOp[] old = getFilters();
    this.filters = new BufferedImageOp[effects.length];
    System.arraycopy(effects, 0, this.filters, 0, this.filters.length);
    setDirty(true);
    firePropertyChange("filters", old, getFilters());
}
Example 51
Project: kolmafia-master  File: JXImageView.java View source code
public void actionPerformed(ActionEvent evt) {
    Image img = getImage();
    BufferedImage src = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    BufferedImage dst = new BufferedImage(img.getHeight(null), img.getWidth(null), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) src.getGraphics();
    try {
        // smooth scaling
        g.drawImage(img, 0, 0, null);
    } finally {
        g.dispose();
    }
    AffineTransform trans = AffineTransform.getRotateInstance(Math.PI / 2, 0, 0);
    trans.translate(0, -src.getHeight());
    BufferedImageOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    op.filter(src, dst);
    setImage(dst);
}
Example 52
Project: NearInfinity-master  File: BamFilterTransformResize.java View source code
// Scales the specified image using Java's native scalers
private BufferedImage scaleNative(BufferedImage srcImage, double factor, int scaleType, boolean paletteSupported) {
    BufferedImage dstImage = srcImage;
    boolean isValid = paletteSupported || srcImage.getType() != BufferedImage.TYPE_BYTE_INDEXED;
    if (isValid && srcImage != null && factor > 0.0 && factor != 1.0) {
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        int newWidth = (int) ((double) width * factor);
        if (newWidth < 1)
            newWidth = 1;
        int newHeight = (int) ((double) height * factor);
        if (newHeight < 1)
            newHeight = 1;
        // preparing target image
        if (paletteSupported && srcImage.getType() == BufferedImage.TYPE_BYTE_INDEXED) {
            IndexColorModel cm = (IndexColorModel) srcImage.getColorModel();
            int[] colors = new int[1 << cm.getPixelSize()];
            cm.getRGBs(colors);
            IndexColorModel cm2 = new IndexColorModel(cm.getPixelSize(), colors.length, colors, 0, cm.hasAlpha(), cm.getTransparentPixel(), DataBuffer.TYPE_BYTE);
            dstImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_BYTE_INDEXED, cm2);
        } else if (srcImage.getType() != BufferedImage.TYPE_BYTE_INDEXED) {
            dstImage = new BufferedImage(newWidth, newHeight, srcImage.getType());
        } else {
            // not supported
            return dstImage;
        }
        // scaling image
        Graphics2D g = dstImage.createGraphics();
        try {
            g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC));
            BufferedImageOp op = new AffineTransformOp(AffineTransform.getScaleInstance(factor, factor), scaleType);
            g.drawImage(srcImage, op, 0, 0);
        } finally {
            g.dispose();
            g = null;
        }
    }
    return dstImage;
}
Example 53
Project: sdrtrunk-master  File: AbstractPainter.java View source code
/**
     * <p>A convenience method for specifying the filters to use based on
     * BufferedImageOps. These will each be individually wrapped by an ImageFilter
     * and then setFilters(Effect... filters) will be called with the resulting
     * array</p>
     * 
     * 
     * @param effects the BufferedImageOps to wrap as filters
     */
public void setFilters(BufferedImageOp... effects) {
    if (effects == null)
        effects = new BufferedImageOp[0];
    BufferedImageOp[] old = getFilters();
    this.filters = new BufferedImageOp[effects.length];
    System.arraycopy(effects, 0, this.filters, 0, this.filters.length);
    setDirty(true);
    firePropertyChange("filters", old, getFilters());
}
Example 54
Project: ultraworm-master  File: FontConverter.java View source code
protected Font doCreate() {
    if (maxChars > Character.MAX_VALUE) {
        maxChars = Character.MAX_VALUE;
    }
    srcFont = java.awt.Font.decode(srcFontName);
    BufferedImage tempImage = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR_PRE);
    Graphics2D gl2d = (Graphics2D) tempImage.getGraphics();
    FontRenderContext frc = gl2d.getFontRenderContext();
    // Create the glyphs for the first MAX_GLYPHS characters
    GlyphVector[] gv = new GlyphVector[maxChars];
    int[] mapping = new int[maxChars];
    boolean[] fixedWidth = new boolean[maxChars];
    gl2d.setFont(srcFont);
    FontMetrics metrics = gl2d.getFontMetrics();
    for (int i = 0; i < maxChars; i++) {
        int[] temp = new int[1];
        temp[0] = i;
        GlyphVector tempgv = srcFont.createGlyphVector(frc, temp);
        gv[i] = tempgv;
    }
    // Work out character mappings
    for (char i = 0; i < maxChars; i++) {
        char[] charToMap = new char[] { i };
        GlyphVector tempgv = srcFont.createGlyphVector(frc, charToMap);
        mapping[i] = tempgv.getGlyphCode(0);
        if (i >= '0' && i <= '9') {
            fixedWidth[mapping[i]] = true;
        }
    }
    // Let's make a guess at what size we need by using 8*width of an M as the width
    // and fitting the characters in:
    int width = Util.nextPowerOf2((int) (8 * srcFont.getStringBounds("M", frc).getWidth()));
    int height = metrics.getHeight();
    int x = 0, y = 0, maxy = 0;
    for (int i = 0; i < maxChars; i++) {
        if (gv[i] == null) {
            continue;
        }
        Shape shape = gv[i].getGlyphOutline(0);
        java.awt.Rectangle bounds = shape.getBounds();
        if (bounds.width == 0 || bounds.height == 0) {
            continue;
        }
        // Start a new row if another character won't fit
        if (x + bounds.width + BORDER + (blur ? 2 : 0) > width) {
            x = 0;
            y += maxy / 2;
            System.out.println("Row height " + maxy + " new height now " + y);
            maxy = 0;
        }
        x += bounds.width + BORDER + (blur ? 2 : 0);
        maxy = Math.max(maxy, bounds.height + BORDER + (blur ? 2 : 0));
    }
    // Now round the height to a legal OpenGL power-of-2
    height = y + maxy / 2;
    System.out.println("Adjusted to " + width + "x" + height + " max height " + (y + maxy));
    while (height >= width && width <= 512) {
        height *= 0.5;
        width *= 2;
    }
    height = Util.nextPowerOf2(y + maxy);
    System.out.println("Adjusted to " + width + "x" + height);
    width = Math.min(1024, width);
    height = Math.min(1024, height);
    // Create a buffered image of this size and set up the font again:
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR_PRE);
    Graphics2D g2d = (Graphics2D) image.getGraphics();
    g2d.setFont(srcFont);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    int numGlyphs = Math.min(maxChars, srcFont.getNumGlyphs());
    Glyph[] glyph = new Glyph[numGlyphs];
    for (int i = 0; i < numGlyphs; i++) {
        glyph[i] = new Glyph();
    }
    GLGraphics2D specialRenderer = new GLGraphics2D();
    x = 0;
    y = 0;
    for (int i = 0; i < numGlyphs; i++) {
        if (gv[i] == null) {
            continue;
        }
        Shape shape = gv[i].getGlyphOutline(0);
        java.awt.Rectangle bounds = shape.getBounds();
        // Because characters are drawn below and to the left of the "origin" (x,y)
        // we need to move them along a wee bit. The translation applied to the bounds
        // here moves the whole rectangle to a (0,0) origin
        int ox = bounds.x;
        int oy = bounds.y;
        // Start a new row if another character won't fit
        if (x + bounds.width + BORDER + (blur ? 2 : 0) >= image.getWidth()) {
            x = 0;
            y += maxy;
            maxy = 0;
        }
        // Draw the glyph so that it doesn't go over any other characters already drawn,
        // by moving it back to a 0,0 origin
        g2d.translate((blur ? 1 : 0) + x - ox, (blur ? 1 : 0) + y - oy);
        g2d.fill(shape);
        if (DEBUG) {
        //				g2d.setColor(Color.RED);
        //				g2d.drawRect(bounds.x, bounds.y, bounds.width - 1, bounds.height - 1);
        //				g2d.drawRect(bounds.x + 1, bounds.y + 1, bounds.width - 3, bounds.height - 3);
        //				g2d.drawRect(bounds.x + 2, bounds.y + 2, bounds.width - 5, bounds.height - 5);
        //				g2d.drawRect(bounds.x + 3, bounds.y + 3, bounds.width - 7, bounds.height - 7);
        //
        //				for (int xxx = 0; xxx < bounds.width - 5; xxx += 4) {
        //					boolean draw = (xxx & 4) == 4;
        //					for (int yyy = 0; yyy < bounds.height - 5; yyy += 4) {
        //						draw = !draw;
        //						if (draw) {
        //							g2d.fillRect(xxx + bounds.x, yyy + bounds.y, 4, 4);
        //						}
        //					}
        //				}
        //
        //				g2d.setColor(Color.WHITE);
        }
        g2d.translate((blur ? -1 : 0) - (x - ox), (blur ? -1 : 0) - (y - oy));
        GlyphMetrics gmetrics = gv[i].getGlyphMetrics(0);
        float glyphAdvance;
        if (fixedWidth[i]) {
            glyphAdvance = gv[mapping['0']].getGlyphMetrics(0).getAdvance();
            ox = (int) ((glyphAdvance - bounds.width) / 2.0f);
        //	System.out.println(ox);
        } else {
            glyphAdvance = gmetrics.getAdvance();
        }
        // Calculate kerning with all other glyphs.
        ArrayList kerningList = new ArrayList();
        ArrayList kernsWithList = new ArrayList();
        for (int left = 0; left < numGlyphs; left++) {
            if (gv[left] == null) {
                continue;
            }
            GlyphVector kerningVector = srcFont.createGlyphVector(frc, new int[] { left, i });
            specialRenderer.reset();
            specialRenderer.drawGlyphVector(kerningVector, 0.0f, 0.0f);
            GlyphMetrics gmetrics2 = gv[left].getGlyphMetrics(0);
            float glyphAdvance2 = gmetrics2.getAdvance();
            float xdif = (specialRenderer.xxx[1] - specialRenderer.xxx[0]);
            if (xdif != glyphAdvance2) {
                kernsWithList.add(glyph[left]);
                kerningList.add(new Integer((int) Math.rint(0.25 + xdif - glyphAdvance2)));
            //System.out.println(i + " kerns with "+left+" : "+ ((int) xdif - glyphAdvance));
            }
        }
        Glyph[] kernsWith;
        int[] kerning;
        if (kerningList.size() > 0) {
            kernsWith = new Glyph[kernsWithList.size()];
            kernsWithList.toArray(kernsWith);
            kerning = new int[kerningList.size()];
            for (int q = 0; q < kerningList.size(); q++) {
                kerning[q] = ((Integer) kerningList.get(q)).intValue();
            }
        } else {
            kernsWith = null;
            kerning = null;
        }
        glyph[i].init(x - (blur ? 1 : 0), y - (blur ? 1 : 0), bounds.width + (blur ? 2 : 0), bounds.height + (blur ? 2 : 0), ox - (blur ? 1 : 0), (-(bounds.height + oy)) - (blur ? 1 : 0), (int) Math.floor(glyphAdvance), kernsWith, kerning);
        // +2 just in case
        x += bounds.width + BORDER + (blur ? 2 : 0);
        maxy = Math.max(maxy, bounds.height + BORDER + (blur ? 2 : 0));
    }
    // Blur the image
    BufferedImage blurredImage;
    if (blur) {
        float[] matrix = { 0.025f, 0.050f, 0.025f, 0.050f, 0.700f, 0.050f, 0.025f, 0.050f, 0.025f };
        BufferedImageOp op = new ConvolveOp(new Kernel(3, 3, matrix));
        blurredImage = op.filter(image, null);
    } else {
        blurredImage = image;
    }
    // Now put buffered image back into font image
    int h = blurredImage.getHeight();
    while (y + maxy < h / 2) {
        h /= 2;
    }
    blurredImage = blurredImage.getSubimage(0, 0, blurredImage.getWidth(), h);
    byte[] newRenderedImage = (byte[]) blurredImage.getRaster().getDataElements(0, 0, blurredImage.getWidth(), blurredImage.getHeight(), null);
    destFont = new Font(srcFont.getName(), srcFont.isBold(), srcFont.isItalic(), new Image(blurredImage.getWidth(), blurredImage.getHeight(), Image.LUMINANCE_ALPHA), glyph, srcFont.getSize(), metrics.getMaxAscent(), metrics.getMaxDescent(), metrics.getLeading(), mapping);
    for (y = 0; y < h; y++) {
        for (x = 0; x < blurredImage.getWidth(); x++) {
            int pos = y * blurredImage.getWidth() * BORDER + x * BORDER;
            byte alpha = newRenderedImage[pos + 3];
            byte img = newRenderedImage[pos + 1];
            destFont.getImage().getData().put(img);
            destFont.getImage().getData().put(alpha);
        }
    }
    destFont.getImage().getData().rewind();
    if (DEBUG) {
        final BufferedImage img = blurredImage;
        new JFrame() {

            private static final long serialVersionUID = 1L;

            {
                addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseClicked(MouseEvent e) {
                        dispose();
                    }
                });
                setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
                setSize(img.getWidth() * 2, img.getHeight() * 2 + 31);
                setVisible(true);
            }

            /* (non-Javadoc)
				 * @see java.awt.Container#paint(java.awt.Graphics)
				 */
            @Override
            public void paint(Graphics g) {
                Graphics2D g2dDebug = (Graphics2D) g;
                g2dDebug.setColor(java.awt.Color.black);
                g2dDebug.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2dDebug.fillRect(0, 32, img.getWidth() * 2, img.getHeight() * 2);
                g2dDebug.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
                g2dDebug.drawImage(img, 0, 31, img.getWidth() * 2, img.getHeight() * 2, this);
            }
        };
    }
    return destFont;
}
Example 55
Project: folio100_frameworks_base-master  File: CommonGraphics2D.java View source code
@Override
public void drawImage(BufferedImage bufImage, BufferedImageOp op, int x, int y) {
    if (bufImage == null) {
        return;
    }
    if (op == null) {
        drawImage(bufImage, x, y, null);
    } else if (op instanceof AffineTransformOp) {
        AffineTransformOp atop = (AffineTransformOp) op;
        AffineTransform xform = atop.getTransform();
        Surface srcSurf = Surface.getImageSurface(bufImage);
        int w = srcSurf.getWidth();
        int h = srcSurf.getHeight();
        blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), xform, composite, null, clip);
    } else {
        bufImage = op.filter(bufImage, null);
        Surface srcSurf = Surface.getImageSurface(bufImage);
        int w = srcSurf.getWidth();
        int h = srcSurf.getHeight();
        blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), composite, null, clip);
    }
}
Example 56
Project: JCGO-master  File: WPathGraphics.java View source code
/**
     * Draws a BufferedImage that is filtered with a BufferedImageOp.
     * The rendering attributes applied include the clip, transform
     * and composite attributes.  This is equivalent to:
     * <pre>
     * img1 = op.filter(img, null);
     * drawImage(img1, new AffineTransform(1f,0f,0f,1f,x,y), null);
     * </pre>
     * @param op The filter to be applied to the image before drawing.
     * @param img The BufferedImage to be drawn.
     * @param x,y The location in user space where the image should be drawn.
     * @see #transform
     * @see #setTransform
     * @see #setComposite
     * @see #clip
     * @see #setClip
     */
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
    boolean result;
    int srcWidth = img.getWidth(null);
    int srcHeight = img.getHeight(null);
    if (op != null) {
        img = op.filter(img, null);
    }
    if (srcWidth < 0 || srcHeight < 0) {
        result = false;
    } else {
        AffineTransform xform = new AffineTransform(1f, 0f, 0f, 1f, x, y);
        result = drawImageToGDI(img, xform, null, null, 0, 0, srcWidth, srcHeight, false);
    }
}
Example 57
Project: LateralGM-master  File: ImageEffects.java View source code
@Override
public BufferedImage getAppliedImage(BufferedImage img) {
    img = Util.convertImage(img, BufferedImage.TYPE_INT_ARGB);
    BufferedImage dst = new BufferedImage(img.getWidth(), img.getHeight(), img.getType());
    Kernel kernel = new Kernel(3, 3, new float[] { -1, -1, -1, -1, 8, -1, -1, -1, -1 });
    BufferedImageOp op = new ConvolveOp(kernel, ConvolveOp.EDGE_ZERO_FILL, null);
    return op.filter(img, dst);
}
Example 58
Project: lilith-master  File: AboutPanel.java View source code
/**
	 * Initializes the scroll-image if needed. The scroll-image is as high as
	 * needed to contain all the scroll-lines and (if available) the image.
	 */
private void initScrollImage() {
    int fontHeight = fontMetrics.getHeight();
    maxScrollPosition = fontHeight * (scrollLines.length);
    int additionalImageOffset = 0;
    int imageWidth = 0;
    if (aboutImage != null) {
        imageWidth = aboutImage.getWidth();
        additionalImageOffset = aboutImage.getHeight() + 2 * fontHeight;
        maxScrollPosition = maxScrollPosition + additionalImageOffset;
    }
    if (scrollImage != null && scrollImage.getHeight() != maxScrollPosition) {
        flushScrollImage();
    }
    if (scrollImage == null) {
        int maxWidth = imageWidth + 2 * fontHeight;
        if (logger.isInfoEnabled())
            logger.info("imageWidth={}, maxWidth={}", imageWidth, maxWidth);
        for (String scrollLine : scrollLines) {
            int curWidth = fontMetrics.stringWidth(scrollLine);
            if (curWidth > maxWidth) {
                maxWidth = curWidth;
            }
        }
        if (maxWidth > maxScrollArea.width) {
            if (logger.isInfoEnabled())
                logger.info("maxWidth={} != maxScrollArea=", maxWidth, maxScrollArea);
            maxWidth = maxScrollArea.width;
        }
        scrollArea.x = maxScrollArea.x + (maxScrollArea.width - maxWidth) / 2;
        scrollArea.y = maxScrollArea.y;
        scrollArea.width = maxWidth;
        scrollArea.height = maxScrollArea.height;
        scrollImage = GraphicsUtilities.createTranslucentCompatibleImage(scrollArea.width, maxScrollPosition);
        Color foreground = getForeground();
        Graphics2D g;
        g = (Graphics2D) scrollImage.getGraphics();
        g.setFont(getFont());
        if (aboutImage != null) {
            g.drawImage(aboutImage, (((scrollArea.width - imageWidth) / 2)), fontHeight, null);
        }
        g.setColor(foreground);
        int y = fontMetrics.getAscent() + additionalImageOffset;
        for (String line : scrollLines) {
            g.drawString(line, (scrollArea.width - fontMetrics.stringWidth(line)) / 2, y);
            y += fontHeight;
        }
        g.dispose();
        BufferedImage copy = GraphicsUtilities.createCompatibleCopy(scrollImage);
        BufferedImageOp filter;
        final int blurSize = 10;
        filter = getGaussianBlurFilter(blurSize, false);
        scrollImage = filter.filter(scrollImage, null);
        filter = getGaussianBlurFilter(blurSize, true);
        scrollImage = filter.filter(scrollImage, null);
        filter = new ColorTintFilter(Color.GREEN, 1.0f);
        scrollImage = filter.filter(scrollImage, null);
        g = (Graphics2D) scrollImage.getGraphics();
        g.setComposite(AlphaComposite.SrcOver);
        g.drawImage(copy, 0, 0, null);
        if (debug) {
            g.setColor(Color.RED);
            g.drawRect(0, 0, scrollImage.getWidth() - 1, scrollImage.getHeight() - 1);
            g.setColor(Color.GREEN);
            g.drawRect((((scrollArea.width - imageWidth) / 2)), fontHeight, aboutImage.getWidth(), aboutImage.getHeight());
        }
        g.dispose();
        copy.flush();
    }
}
Example 59
Project: oculusPrime-master  File: AutoDock.java View source code
public void run() {
    int n = 0;
    while (state.getBoolean(State.values.framegrabbusy)) {
        Util.delay(5);
        n++;
        // give up after 10 seconds
        if (n > 2000) {
            Util.log("error, frame grab timed out", this);
            state.set(State.values.framegrabbusy, false);
            break;
        }
    }
    BufferedImage img = null;
    if (// TODO: unused?
    Application.framegrabimg != null) {
        // convert bytes to image
        ByteArrayInputStream in = new ByteArrayInputStream(Application.framegrabimg);
        try {
            img = ImageIO.read(in);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (Application.processedImage != null) {
        img = Application.processedImage;
    } else {
        Util.log("dockgrab() framegrab failure", this);
        return;
    }
    imgwidth = img.getWidth();
    imgheight = img.getHeight();
    // for clicksteer gui 640 window
    rescomp = 640 / imgwidth;
    float[] matrix = { 0.111f, 0.111f, 0.111f, 0.111f, 0.111f, 0.111f, 0.111f, 0.111f, 0.111f };
    BufferedImageOp op = new ConvolveOp(new Kernel(3, 3, matrix));
    img = op.filter(img, new BufferedImage(imgwidth, imgheight, BufferedImage.TYPE_INT_ARGB));
    int[] argb = img.getRGB(0, 0, imgwidth, imgheight, null, 0, imgwidth);
    String[] results;
    String str;
    switch(mode) {
        case calibrate:
            results = oculusImage.findBlobStart(x, y, img.getWidth(), img.getHeight(), argb);
            autoDock(autodockmodes.dockgrabbed.toString() + " " + dockgrabmodes.calibrate.toString() + " " + results[0] + " " + results[1] + " " + results[2] + " " + results[3] + " " + results[4] + " " + results[5] + " " + results[6] + " " + results[7] + " " + results[8]);
            break;
        case start:
            oculusImage.lastThreshhold = -1;
        case find:
            results = oculusImage.findBlobs(argb, imgwidth, imgheight);
            str = results[0] + " " + results[1] + " " + results[2] + " " + results[3] + " " + results[4];
            // results = x,y,width,height,slope
            int width = Integer.parseInt(results[2]);
            // also here because nav timer relys on dockfound
            state.set(State.values.dockgrabbusy.name(), false);
            // interpret results
            if (width < (int) (0.02 * imgwidth) || width > (int) (0.875 * imgwidth) || results[3].equals("0"))
                // failed to find target! unrealistic widths
                state.set(State.values.dockfound, false);
            else {
                state.set(// success!
                State.values.dockfound, true);
                state.set(State.values.dockmetrics, str);
            }
            if (state.getBoolean(State.values.autodocking))
                autoDock(autodockmodes.dockgrabbed.toString() + " " + dockgrabmodes.find.toString() + " " + str);
            break;
        case test:
            oculusImage.lastThreshhold = -1;
            results = oculusImage.findBlobs(argb, imgwidth, imgheight);
            int guix = Integer.parseInt(results[0]) / (2 / rescomp);
            int guiy = Integer.parseInt(results[1]) / (2 / rescomp);
            int guiw = Integer.parseInt(results[2]) / (2 / rescomp);
            int guih = Integer.parseInt(results[3]) / (2 / rescomp);
            str = guix + " " + guiy + " " + guiw + " " + guih + " " + results[4];
            // results = x,y,width,height,slope
            app.message(str, "autodocklock", str);
            break;
    }
    state.set(State.values.dockgrabbusy, false);
}
Example 60
Project: open-mika-master  File: CommonGraphics2D.java View source code
@Override
public void drawImage(BufferedImage bufImage, BufferedImageOp op, int x, int y) {
    if (bufImage == null) {
        return;
    }
    if (op == null) {
        drawImage(bufImage, x, y, null);
    } else if (op instanceof AffineTransformOp) {
        AffineTransformOp atop = (AffineTransformOp) op;
        AffineTransform xform = atop.getTransform();
        Surface srcSurf = Surface.getImageSurface(bufImage);
        int w = srcSurf.getWidth();
        int h = srcSurf.getHeight();
        blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), xform, composite, null, clip);
    } else {
        bufImage = op.filter(bufImage, null);
        Surface srcSurf = Surface.getImageSurface(bufImage);
        int w = srcSurf.getWidth();
        int h = srcSurf.getHeight();
        blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), composite, null, clip);
    }
}
Example 61
Project: PDFrenderer-master  File: PDFRenderer.java View source code
private Rectangle2D smartDrawImage(PDFImage image, BufferedImage bi, Rectangle r, AffineTransform at) {
    boolean isBlured = false;
    if (Configuration.getInstance().isUseBlurResizingForImages() && bi.getType() != BufferedImage.TYPE_CUSTOM && image.getWidth() >= 1.75 * r.getWidth() && image.getHeight() >= 1.75 * r.getHeight()) {
        BufferedImageOp op;
        // indexed colored images need to be converted for the convolveOp
        boolean colorConversion = (bi.getColorModel() instanceof IndexColorModel);
        final float maxFactor = 3.5f;
        final boolean RESIZE = true;
        if (image.getWidth() > maxFactor * r.getWidth() && image.getHeight() > maxFactor * r.getHeight()) {
            //First resize, otherwise we risk that we get out of heapspace
            int newHeight = (int) Math.round(maxFactor * r.getHeight());
            int newWidth = (int) Math.round(maxFactor * r.getWidth());
            if (!RESIZE) {
                newHeight = image.getHeight();
                newWidth = image.getWidth();
            }
            BufferedImage resized = new BufferedImage(newWidth, newHeight, colorConversion ? BufferedImage.TYPE_INT_ARGB : bi.getType());
            Graphics2D bg = (Graphics2D) resized.getGraphics();
            bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            bg.drawImage(bi, 0, 0, newWidth, newHeight, null);
            bi = resized;
            at = new AffineTransform(1f / bi.getWidth(), 0, 0, -1f / bi.getHeight(), 0, 1);
            final float weight = 1.0f / 16.0f;
            final float[] blurKernel = { weight, weight, weight, weight, weight, weight, weight, weight, weight, weight, weight, weight, weight, weight, weight, weight };
            op = new ConvolveOp(new Kernel(4, 4, blurKernel), ConvolveOp.EDGE_NO_OP, null);
        } else {
            final float weight = 1.0f / 18.0f;
            final float[] blurKernel = { 1 * weight, 2 * weight, 1 * weight, 2 * weight, 6 * weight, 2 * weight, 1 * weight, 2 * weight, 1 * weight };
            if (colorConversion) {
                BufferedImage colored = new BufferedImage(image.getWidth(), image.getHeight(), colorConversion ? BufferedImage.TYPE_INT_ARGB : bi.getType());
                Graphics2D bg = (Graphics2D) colored.getGraphics();
                bg.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                bg.drawImage(bi, 0, 0, image.getWidth(), image.getHeight(), null);
                bi = colored;
            }
            op = new ConvolveOp(new Kernel(3, 3, blurKernel), ConvolveOp.EDGE_NO_OP, null);
        }
        BufferedImage blured = op.createCompatibleDestImage(bi, colorConversion ? ColorModel.getRGBdefault() : bi.getColorModel());
        op.filter(bi, blured);
        bi = blured;
        isBlured = true;
    }
    this.g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
    //Image quality is better when using texturepaint instead of drawimage
    //but it is also slower :(
    this.g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    // banded rendering may lead to lower memory consumption for e.g. scanned PDFs with large images
    int bandSize = Configuration.getInstance().getThresholdForBandedImageRendering();
    if (bandSize > 0 && bi.getHeight() > bandSize) {
        // draw in bands
        int tempMax = bi.getHeight();
        for (int offset = 0; offset < tempMax; offset += bandSize) {
            int h = Math.min(tempMax - offset, bandSize);
            AffineTransform translated = AffineTransform.getTranslateInstance(0, -(double) offset / tempMax);
            translated.concatenate(at);
            if (!g.drawImage(bi.getSubimage(0, offset, bi.getWidth(), h), translated, null)) {
                PDFDebugger.debug("Image part not completed!", 10);
            }
        }
    } else {
        if (!g.drawImage(bi, at, null)) {
            PDFDebugger.debug("Image not completed!", 10);
        }
    }
    if (isBlured)
        bi.flush();
    // get the total transform that was executed
    AffineTransform bt = new AffineTransform(this.g.getTransform());
    bt.concatenate(at);
    double minx = bi.getMinX();
    double miny = bi.getMinY();
    double[] points = new double[] { minx, miny, minx + bi.getWidth(), miny + bi.getHeight() };
    bt.transform(points, 0, points, 0, 2);
    return new Rectangle2D.Double(points[0], points[1], points[2] - points[0], points[3] - points[1]);
}
Example 62
Project: swagd-master  File: RawImageTileReader.java View source code
private BufferedImage scaleToTileCanvas(final BufferedImage fullCanvas) {
    final BufferedImage tileCanvas = new BufferedImage(RawImageTileReader.this.tileSize.getWidth(), RawImageTileReader.this.tileSize.getHeight(), BufferedImage.TYPE_INT_ARGB);
    final AffineTransform affineTransform = new AffineTransform();
    affineTransform.scale(AFFINE_SCALE, AFFINE_SCALE);
    final BufferedImageOp scaleOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_BILINEAR);
    return scaleOp.filter(fullCanvas, tileCanvas);
}
Example 63
Project: WS171-frameworks-base-master  File: CommonGraphics2D.java View source code
@Override
public void drawImage(BufferedImage bufImage, BufferedImageOp op, int x, int y) {
    if (bufImage == null) {
        return;
    }
    if (op == null) {
        drawImage(bufImage, x, y, null);
    } else if (op instanceof AffineTransformOp) {
        AffineTransformOp atop = (AffineTransformOp) op;
        AffineTransform xform = atop.getTransform();
        Surface srcSurf = Surface.getImageSurface(bufImage);
        int w = srcSurf.getWidth();
        int h = srcSurf.getHeight();
        blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), xform, composite, null, clip);
    } else {
        bufImage = op.filter(bufImage, null);
        Surface srcSurf = Surface.getImageSurface(bufImage);
        int w = srcSurf.getWidth();
        int h = srcSurf.getHeight();
        blitter.blit(0, 0, srcSurf, x, y, dstSurf, w, h, (AffineTransform) transform.clone(), composite, null, clip);
    }
}
Example 64
Project: LGA-master  File: GraphicsUtils.java View source code
public static BufferedImage rotateImage(final BufferedImage image, final int degrees) {
    AffineTransform at = new AffineTransform();
    at.rotate(degrees < 0 ? -Math.toRadians(degrees) : Math.toRadians(degrees), image.getWidth() / 2, image.getHeight() / 2);
    BufferedImageOp bio = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
    BufferedImage dest = bio.filter(image, null);
    return dest;
}
Example 65
Project: LGame-master  File: GraphicsUtils.java View source code
public static BufferedImage rotateImage(final BufferedImage image, final int degrees) {
    AffineTransform at = new AffineTransform();
    at.rotate(degrees < 0 ? -Math.toRadians(degrees) : Math.toRadians(degrees), image.getWidth() / 2, image.getHeight() / 2);
    BufferedImageOp bio = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
    BufferedImage dest = bio.filter(image, null);
    return dest;
}
Example 66
Project: RipplePower-master  File: GraphicsUtils.java View source code
public static BufferedImage rotateImage(final BufferedImage image, final int degrees) {
    AffineTransform at = new AffineTransform();
    at.rotate(degrees < 0 ? -Math.toRadians(degrees) : Math.toRadians(degrees), image.getWidth() / 2, image.getHeight() / 2);
    BufferedImageOp bio = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
    BufferedImage dest = bio.filter(image, null);
    return dest;
}
Example 67
Project: VUE-master  File: LWIcon.java View source code
void draw(DrawContext dc) {
    if (false && DEBUG.Enabled) {
        // test code for inserting actual icon into node icon gutter (should at least do by
        // default for local file icons)
        Icon icon = mLWC.getResource().getContentIcon();
        if (icon instanceof ResourceIcon) {
            ((ResourceIcon) icon).setSize((int) Math.round(getWidth() - 4), (int) Math.round(getHeight()));
            icon.paintIcon(null, dc.g, (int) Math.round(getX() + 2), (int) Math.round(getY() + 2));
            super.draw(dc);
            return;
        }
    }
    if (// TODO PERF: sometimes starts with boxBounds wrong...
    true || extension == null)
        internalLayout();
    super.draw(dc);
    if (dc.isIndicated(mLWC)) {
        dc.g.setColor(Color.white);
        dc.g.fill(boxBounds);
        dc.g.setColor(Color.gray);
        dc.g.setStroke(STROKE_HALF);
        dc.g.draw(boxBounds);
        // Leave an empty box:
        return;
    }
    // System.out.println("CHECK PDF RENDERING");
    if (!dc.isInteractive()) {
        //	System.out.println("PDF RENDERING");
        dc.g.setRenderingHint(PdfGraphics2D.HyperLinkKey.KEY_INSTANCE, mLWC.getResource().getSpec());
        BufferedImage bi = new BufferedImage((int) getWidth(), (int) getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics g = bi.createGraphics();
        if (g instanceof Graphics2D) {
            Graphics2D g2d = (Graphics2D) g;
            // make sure the background is filled with transparent pixels when cleared !
            g2d.setBackground(new Color(0, 0, 0, 0));
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, 0.0f));
            g2d.clearRect(0, 0, (int) getWidth(), (int) getHeight());
        }
        dc.g.drawImage(bi, (BufferedImageOp) null, (int) getX(), (int) getY());
        dc.g.setRenderingHint(PdfGraphics2D.HyperLinkKey.KEY_INSTANCE, PdfGraphics2D.HyperLinkKey.VALUE_HYPERLINKKEY_OFF);
    }
    // TODO PERF: if BoxFill has alpha, pre-mix it with node.getRenderFillColor()
    // todo: getContrastColor(dc)
    final Color fill = mLWC.getRenderFillColor(dc);
    //             if (mLWC instanceof LWLink)
    //                 dc.g.setColor(fill);
    //             else
    dc.g.setColor(BoxFill);
    dc.g.fill(boxBounds);
    //dc.g.setColor(BoxBorder);
    dc.g.setColor(fill == null ? Color.gray : fill.darker());
    dc.g.setStroke(STROKE_HALF);
    dc.g.draw(boxBounds);
    dc.g.setColor(mColor);
    dc.g.setFont(FONT_ICON);
    //             String extension = NoResource;
    //             if (mLWC.hasResource())
    //                 extension = mLWC.getResource().getExtension();
    double x = getX();
    double y = getY();
    dc.g.translate(x, y);
    // todo perf: listen for resource change & cache text row
    //TextRow row = new TextRow(extension, dc.g);
    final TextRow row = mTextRow;
    // Resource icon special case can override parent set width:
    if (super.width < row.width)
        super.width = row.width;
    final float xoff = (super.width - row.width) / 2;
    final float yoff = (super.height - row.height) / 2;
    row.draw(dc, xoff, yoff);
    //             // an experiment in semantic zoom
    //             //if (dc.zoom >= 8.0 && mLWC.hasResource()) {
    //             if (mLWC.hasResource() && dc.g.getTransform().getScaleX() >= 8.0) {
    //                 dc.g.setFont(MinisculeFont);
    //                 dc.g.setColor(Color.gray);
    //                 dc.g.drawString(mLWC.getResource().toString(), 0, (int)(super.height));
    //             }
    dc.g.translate(-x, -y);
//MK  System.out.println("K");
}
Example 68
Project: consulo-master  File: UIUtil.java View source code
public static void drawImage(Graphics g, BufferedImage image, BufferedImageOp op, int x, int y) {
    if (image instanceof JBHiDPIScaledImage) {
        final Graphics2D newG = (Graphics2D) g.create(x, y, image.getWidth(null), image.getHeight(null));
        newG.scale(0.5, 0.5);
        Image img = ((JBHiDPIScaledImage) image).getDelegate();
        if (img == null) {
            img = image;
        }
        newG.drawImage((BufferedImage) img, op, 0, 0);
        //newG.scale(1, 1);
        newG.dispose();
    } else {
        ((Graphics2D) g).drawImage(image, op, x, y);
    }
}
Example 69
Project: Desktop-master  File: Scalr.java View source code
/**
	 * Resize a given image (maintaining its original proportion) to the target
	 * width and height (or fitting the image to the given WIDTH or HEIGHT
	 * explicitly, depending on the {@link Mode} specified) using the given
	 * scaling method, apply the given {@link BufferedImageOp}s (if any) and
	 * apply the given rotation to the result before returning it.
	 * <p/>
	 * <strong>TIP</strong>: See the class description to understand how this
	 * class handles recalculation of the <code>targetWidth</code> or
	 * <code>targetHeight</code> depending on the image's orientation in order
	 * to maintain the original proportion.
	 * <p/>
	 * <strong>Performance</strong>: Not all {@link BufferedImageOp}s are
	 * hardware accelerated operations, but many of the most popular (like
	 * {@link ConvolveOp}) are. For more information on if your image op is
	 * hardware accelerated or not, check the source code of the underlying JDK
	 * class that actually executes the Op code, <a href=
	 * "http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html"
	 * >sun.awt.image.ImagingLib</a>.
	 *
	 * @param src
	 *            The image that will be scaled.
	 * @param scalingMethod
	 *            The method used for scaling the image; preferring speed to
	 *            quality or a balance of both.
	 * @param resizeMode
	 *            Used to indicate how imgscalr should calculate the final
	 *            target size for the image, either fitting the image to the
	 *            given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image
	 *            to the given height ({@link Mode#FIT_TO_HEIGHT}). If
	 *            {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate
	 *            proportional dimensions for the scaled image based on its
	 *            orientation (landscape, square or portrait). Unless you have
	 *            very specific size requirements, most of the time you just
	 *            want to use {@link Mode#AUTOMATIC} to "do the right thing".
	 * @param rotation
	 *            The rotation to be applied to the scaled image right before it
	 *            is returned.
	 * @param targetWidth
	 *            The target width that you wish the image to have.
	 * @param targetHeight
	 *            The target height that you wish the image to have.
	 * @param ops
	 *            Zero or more optional image operations (e.g. sharpen, blur,
	 *            etc.) that can be applied to the final result before returning
	 *            the image.
	 *
	 * @return the proportionally scaled image no bigger than the given width
	 *         and height.
	 *
	 * @throws IllegalArgumentException
	 *             if <code>src</code> is <code>null</code>.
	 * @throws IllegalArgumentException
	 *             if <code>scalingMethod</code> is <code>null</code>.
	 * @throws IllegalArgumentException
	 *             if <code>resizeMode</code> is <code>null</code>.
	 * @throws IllegalArgumentException
	 *             if <code>rotation</code> is <code>null</code>.
	 * @throws IllegalArgumentException
	 *             if <code>targetWidth</code> is < 0 or if
	 *             <code>targetHeight</code> is < 0.
	 *
	 * @see Method
	 * @see Mode
	 * @see Rotation
	 * @see #OP_ANTIALIAS
	 */
public static BufferedImage resize(BufferedImage src, Method scalingMethod, Mode resizeMode, Rotation rotation, int targetWidth, int targetHeight, BufferedImageOp... ops) throws IllegalArgumentException {
    if (src == null)
        throw new IllegalArgumentException("src cannot be null, a valid BufferedImage instance must be provided.");
    if (scalingMethod == null)
        throw new IllegalArgumentException("scalingMethod cannot be null. A good default value is Method.AUTOMATIC.");
    if (resizeMode == null)
        throw new IllegalArgumentException("resizeMode cannot be null. A good default value is Mode.AUTOMATIC.");
    if (rotation == null)
        throw new IllegalArgumentException("rotation cannot be null. A good default value is Rotation.NONE.");
    if (targetWidth < 0)
        throw new IllegalArgumentException("targetWidth must be >= 0");
    if (targetHeight < 0)
        throw new IllegalArgumentException("targetHeight must be >= 0");
    BufferedImage result = null;
    long startTime = System.currentTimeMillis();
    // Clear the 'null' ops arg passed in from other API methods
    if (ops != null && ops.length == 1 && ops[0] == null)
        ops = null;
    int currentWidth = src.getWidth();
    int currentHeight = src.getHeight();
    // <= 1 is a square or landscape-oriented image, > 1 is a portrait.
    float ratio = ((float) currentHeight / (float) currentWidth);
    if (DEBUG)
        log("START Resizing Source Image [size=%dx%d, mode=%s, orientation=%s, ratio(H/W)=%f] to [targetSize=%dx%d]", currentWidth, currentHeight, resizeMode, (ratio <= 1 ? "Landscape/Square" : "Portrait"), ratio, targetWidth, targetHeight);
    /*
		 * The proportion of the picture must be honored, the way that is done
		 * is to figure out if the image is in a LANDSCAPE/SQUARE or PORTRAIT
		 * orientation and depending on its orientation, use the primary
		 * dimension (width for LANDSCAPE/SQUARE and height for PORTRAIT) to
		 * recalculate the alternative (height and width respectively) value
		 * that adheres to the existing ratio. This helps make life easier for
		 * the caller as they don't need to pre-compute proportional dimensions
		 * before calling the API, they can just specify the dimensions they
		 * would like the image to roughly fit within and it will do the right
		 * thing without mangling the result.
		 */
    if ((ratio <= 1 && resizeMode == Mode.AUTOMATIC) || (resizeMode == Mode.FIT_TO_WIDTH)) {
        // First make sure we need to do any work in the first place
        if (targetWidth == src.getWidth())
            return src;
        // Save for detailed logging (this is cheap).
        int originalTargetHeight = targetHeight;
        /*
			 * Landscape or Square Orientation: Ignore the given height and
			 * re-calculate a proportionally correct value based on the
			 * targetWidth.
			 */
        targetHeight = Math.round((float) targetWidth * ratio);
        if (DEBUG && originalTargetHeight != targetHeight)
            log("Auto-Corrected targetHeight [from=%d to=%d] to honor image proportions", originalTargetHeight, targetHeight);
    } else {
        // First make sure we need to do any work in the first place
        if (targetHeight == src.getHeight())
            return src;
        // Save for detailed logging (this is cheap).
        int originalTargetWidth = targetWidth;
        /*
			 * Portrait Orientation: Ignore the given width and re-calculate a
			 * proportionally correct value based on the targetHeight.
			 */
        targetWidth = Math.round((float) targetHeight / ratio);
        if (DEBUG && originalTargetWidth != targetWidth)
            log("Auto-Corrected targetWidth [from=%d to=%d] to honor image proportions", originalTargetWidth, targetWidth);
    }
    // If AUTOMATIC was specified, determine the real scaling method.
    if (scalingMethod == Scalr.Method.AUTOMATIC)
        scalingMethod = determineScalingMethod(targetWidth, targetHeight, ratio);
    if (DEBUG)
        log("Scaling Image to [size=%dx%d] using the %s method...", targetWidth, targetHeight, scalingMethod);
    // Now we scale the image
    if (scalingMethod == Scalr.Method.SPEED) {
        result = scaleImage(src, targetWidth, targetHeight, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
    } else if (scalingMethod == Scalr.Method.BALANCED) {
        result = scaleImage(src, targetWidth, targetHeight, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    } else if (scalingMethod == Scalr.Method.QUALITY) {
        /*
			 * If we are scaling up (in either width or height - since we know
			 * the image will stay proportional we just check if either are
			 * being scaled up), directly using a single BICUBIC will give us
			 * better results then using Chris Campbell's incremental scaling
			 * operation (and take a lot less time). If we are scaling down, we
			 * must use the incremental scaling algorithm for the best result.
			 */
        if (targetWidth > currentWidth || targetHeight > currentHeight) {
            log("\tQUALITY Up-scale, single BICUBIC scaling will be used...");
            /*
				 * BILINEAR and BICUBIC look similar the smaller the scale jump
				 * upwards is, if the scale is larger BICUBIC looks sharper and
				 * less fuzzy. But most importantly we have to use BICUBIC to
				 * match the contract of the QUALITY rendering method. This note
				 * is just here for anyone reading the code and wondering how
				 * they can speed their own calls up.
				 */
            result = scaleImage(src, targetWidth, targetHeight, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        } else {
            log("\tQUALITY Down-scale, incremental scaling will be used...");
            /*
				 * Originally we wanted to use BILINEAR interpolation here
				 * because it takes 1/3rd the time that the BICUBIC
				 * interpolation does, however, when scaling large images down
				 * to most sizes bigger than a thumbnail we witnessed noticeable
				 * "softening" in the resultant image with BILINEAR that would
				 * be unexpectedly annoying to a user expecting a "QUALITY"
				 * scale of their original image. Instead BICUBIC was chosen to
				 * honor the contract of a QUALITY scale of the original image.
				 */
            result = scaleImageIncrementally(src, targetWidth, targetHeight, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        }
    }
    // Apply the image ops if any were provided
    if (ops != null && ops.length > 0) {
        if (DEBUG)
            log("Applying %d Image Ops to Result", ops.length);
        for (BufferedImageOp op : ops) {
            // In case a null op was passed in, skip it instead of dying
            if (op == null)
                continue;
            long opStartTime = System.currentTimeMillis();
            Rectangle2D dims = op.getBounds2D(result);
            /*
				 * We must manually create the target image; we cannot rely on
				 * the null-dest filter() method to create a valid destination
				 * for us thanks to this JDK bug that has been filed for almost
				 * a decade:
				 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606
				 */
            BufferedImage dest = new BufferedImage((int) Math.round(dims.getWidth()), (int) Math.round(dims.getHeight()), result.getType());
            result = op.filter(result, dest);
            if (DEBUG)
                log("\tOp Applied in %d ms, Resultant Image [width=%d, height=%d], Op: %s", (System.currentTimeMillis() - opStartTime), result.getWidth(), result.getHeight(), op);
        }
    }
    // Perform the rotation if one was requested
    if (rotation != Rotation.NONE) {
        if (DEBUG)
            log("Applying %s rotation to image...", rotation);
        long rotStartTime = System.currentTimeMillis();
        /*
			 * A 90 or -90 degree rotation will cause the height and width to
			 * flip-flop from the original image to the rotated one.
			 *
			 * Given that MOST rotations will typically be some form of a
			 * 90-degree rotation (portrait to landscape, etc.) just assume that
			 * here and correct it below in the switch statement if need be.
			 */
        int newWidth = result.getHeight();
        int newHeight = result.getWidth();
        /*
			 * We create a transform per operation request as (oddly enough) it
			 * ends up being faster for the VM to create, use and destroy these
			 * instances than it is to re-use a single AffineTransform
			 * per-thread via the AffineTransform.setTo(...) methods which was
			 * my first choice (less object creation).
			 *
			 * Unfortunately this introduces the need for ThreadLocal instances
			 * of AffineTransforms to avoid race conditions where two or more
			 * resize threads are manipulating the same transform before
			 * applying it.
			 *
			 * ThreadLocals are one of the #1 reasons for memory leaks in server
			 * applications and since we have no nice way to hook into the
			 * init/destroy Servlet cycle or any other initialization cycle for
			 * this library to automatically call ThreadLocal.remove() to avoid
			 * the memory leak, it would have made using this library *safely*
			 * on the server side much harder.
			 *
			 * So we opt for creating individual transforms per rotation op and
			 * let the VM clean them up in a GC.
			 */
        AffineTransform tx = new AffineTransform();
        switch(rotation) {
            case CLOCKWISE:
                // Reminder: newWidth == result.getHeight() at this point
                tx.translate(newWidth, 0);
                tx.rotate(Math.toRadians(90));
                break;
            case COUNTER_CLOCKWISE:
                // Reminder: newHeight == result.getWidth() at this point
                tx.translate(0, newHeight);
                tx.rotate(Math.toRadians(-90));
                break;
            case FLIP:
                /*
				 * This is the one rotation case where the new width and height
				 * will be the same as the original image, so reset the values
				 * from the defaults we set above.
				 */
                newWidth = result.getWidth();
                newHeight = result.getHeight();
                tx.translate(newWidth, newHeight);
                tx.rotate(Math.toRadians(180));
                break;
        }
        /*
			 * Create our target image we will render the rotated result to. At
			 * this point the resultant image has already been put into the best
			 * image type so we can just copy that without trying to
			 * re-determine the most effective image type like scaleImage(...)
			 * has to do.
			 */
        BufferedImage rotatedImage = new BufferedImage(newWidth, newHeight, result.getType());
        Graphics2D g2d = (Graphics2D) rotatedImage.createGraphics();
        /*
			 * Render the resultant image to our new rotatedImage buffer,
			 * applying the AffineTransform that we calculated above during
			 * rendering so the pixels from the old position to the new
			 * transposed positions are mapped correctly.
			 */
        g2d.drawImage(result, tx, null);
        g2d.dispose();
        /*
			 * Before re-assigning the new result to be returned to our rotated
			 * image, explicitly notify the VM that you are done with any
			 * resources being used by the old resultant image that we don't
			 * need anymore.
			 */
        result.flush();
        // Reassign the result to our rotated image before returning it.
        result = rotatedImage;
        if (DEBUG)
            log("\t%s Rotation Applied in %d ms, Resultant Image [width=%d, height=%d]", rotation, (System.currentTimeMillis() - rotStartTime), result.getWidth(), result.getHeight());
    }
    if (DEBUG) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        log("END Source Image Scaled from [%dx%d] to [%dx%d] and %d BufferedImageOp(s) Applied in %d ms", currentWidth, currentHeight, result.getWidth(), result.getHeight(), (ops == null ? 0 : ops.length), elapsedTime);
    }
    return result;
}
Example 70
Project: Docear-master  File: Scalr.java View source code
/**
	 * Resize a given image (maintaining its original proportion) to the target
	 * width and height (or fitting the image to the given WIDTH or HEIGHT
	 * explicitly, depending on the {@link Mode} specified) using the given
	 * scaling method, apply the given {@link BufferedImageOp}s (if any) and
	 * apply the given rotation to the result before returning it.
	 * <p/>
	 * <strong>TIP</strong>: See the class description to understand how this
	 * class handles recalculation of the <code>targetWidth</code> or
	 * <code>targetHeight</code> depending on the image's orientation in order
	 * to maintain the original proportion.
	 * <p/>
	 * <strong>Performance</strong>: Not all {@link BufferedImageOp}s are
	 * hardware accelerated operations, but many of the most popular (like
	 * {@link ConvolveOp}) are. For more information on if your image op is
	 * hardware accelerated or not, check the source code of the underlying JDK
	 * class that actually executes the Op code, <a href=
	 * "http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html"
	 * >sun.awt.image.ImagingLib</a>.
	 *
	 * @param src
	 *            The image that will be scaled.
	 * @param scalingMethod
	 *            The method used for scaling the image; preferring speed to
	 *            quality or a balance of both.
	 * @param resizeMode
	 *            Used to indicate how imgscalr should calculate the final
	 *            target size for the image, either fitting the image to the
	 *            given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image
	 *            to the given height ({@link Mode#FIT_TO_HEIGHT}). If
	 *            {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate
	 *            proportional dimensions for the scaled image based on its
	 *            orientation (landscape, square or portrait). Unless you have
	 *            very specific size requirements, most of the time you just
	 *            want to use {@link Mode#AUTOMATIC} to "do the right thing".
	 * @param rotation
	 *            The rotation to be applied to the scaled image right before it
	 *            is returned.
	 * @param targetWidth
	 *            The target width that you wish the image to have.
	 * @param targetHeight
	 *            The target height that you wish the image to have.
	 * @param ops
	 *            Zero or more optional image operations (e.g. sharpen, blur,
	 *            etc.) that can be applied to the final result before returning
	 *            the image.
	 *
	 * @return the proportionally scaled image no bigger than the given width
	 *         and height.
	 *
	 * @throws IllegalArgumentException
	 *             if <code>src</code> is <code>null</code>.
	 * @throws IllegalArgumentException
	 *             if <code>scalingMethod</code> is <code>null</code>.
	 * @throws IllegalArgumentException
	 *             if <code>resizeMode</code> is <code>null</code>.
	 * @throws IllegalArgumentException
	 *             if <code>rotation</code> is <code>null</code>.
	 * @throws IllegalArgumentException
	 *             if <code>targetWidth</code> is < 0 or if
	 *             <code>targetHeight</code> is < 0.
	 *
	 * @see Method
	 * @see Mode
	 * @see Rotation
	 * @see #OP_ANTIALIAS
	 */
public static BufferedImage resize(BufferedImage src, Method scalingMethod, Mode resizeMode, Rotation rotation, int targetWidth, int targetHeight, BufferedImageOp... ops) throws IllegalArgumentException {
    if (src == null)
        throw new IllegalArgumentException("src cannot be null, a valid BufferedImage instance must be provided.");
    if (scalingMethod == null)
        throw new IllegalArgumentException("scalingMethod cannot be null. A good default value is Method.AUTOMATIC.");
    if (resizeMode == null)
        throw new IllegalArgumentException("resizeMode cannot be null. A good default value is Mode.AUTOMATIC.");
    if (rotation == null)
        throw new IllegalArgumentException("rotation cannot be null. A good default value is Rotation.NONE.");
    if (targetWidth < 0)
        throw new IllegalArgumentException("targetWidth must be >= 0");
    if (targetHeight < 0)
        throw new IllegalArgumentException("targetHeight must be >= 0");
    BufferedImage result = null;
    long startTime = System.currentTimeMillis();
    // Clear the 'null' ops arg passed in from other API methods
    if (ops != null && ops.length == 1 && ops[0] == null)
        ops = null;
    int currentWidth = src.getWidth();
    int currentHeight = src.getHeight();
    // <= 1 is a square or landscape-oriented image, > 1 is a portrait.
    float ratio = ((float) currentHeight / (float) currentWidth);
    if (DEBUG)
        log("START Resizing Source Image [size=%dx%d, mode=%s, orientation=%s, ratio(H/W)=%f] to [targetSize=%dx%d]", currentWidth, currentHeight, resizeMode, (ratio <= 1 ? "Landscape/Square" : "Portrait"), ratio, targetWidth, targetHeight);
    /*
		 * The proportion of the picture must be honored, the way that is done
		 * is to figure out if the image is in a LANDSCAPE/SQUARE or PORTRAIT
		 * orientation and depending on its orientation, use the primary
		 * dimension (width for LANDSCAPE/SQUARE and height for PORTRAIT) to
		 * recalculate the alternative (height and width respectively) value
		 * that adheres to the existing ratio. This helps make life easier for
		 * the caller as they don't need to pre-compute proportional dimensions
		 * before calling the API, they can just specify the dimensions they
		 * would like the image to roughly fit within and it will do the right
		 * thing without mangling the result.
		 */
    if ((ratio <= 1 && resizeMode == Mode.AUTOMATIC) || (resizeMode == Mode.FIT_TO_WIDTH)) {
        // First make sure we need to do any work in the first place
        if (targetWidth == src.getWidth())
            return src;
        // Save for detailed logging (this is cheap).
        int originalTargetHeight = targetHeight;
        /*
			 * Landscape or Square Orientation: Ignore the given height and
			 * re-calculate a proportionally correct value based on the
			 * targetWidth.
			 */
        targetHeight = Math.round((float) targetWidth * ratio);
        if (DEBUG && originalTargetHeight != targetHeight)
            log("Auto-Corrected targetHeight [from=%d to=%d] to honor image proportions", originalTargetHeight, targetHeight);
    } else {
        // First make sure we need to do any work in the first place
        if (targetHeight == src.getHeight())
            return src;
        // Save for detailed logging (this is cheap).
        int originalTargetWidth = targetWidth;
        /*
			 * Portrait Orientation: Ignore the given width and re-calculate a
			 * proportionally correct value based on the targetHeight.
			 */
        targetWidth = Math.round((float) targetHeight / ratio);
        if (DEBUG && originalTargetWidth != targetWidth)
            log("Auto-Corrected targetWidth [from=%d to=%d] to honor image proportions", originalTargetWidth, targetWidth);
    }
    // If AUTOMATIC was specified, determine the real scaling method.
    if (scalingMethod == Scalr.Method.AUTOMATIC)
        scalingMethod = determineScalingMethod(targetWidth, targetHeight, ratio);
    if (DEBUG)
        log("Scaling Image to [size=%dx%d] using the %s method...", targetWidth, targetHeight, scalingMethod);
    // Now we scale the image
    if (scalingMethod == Scalr.Method.SPEED) {
        result = scaleImage(src, targetWidth, targetHeight, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
    } else if (scalingMethod == Scalr.Method.BALANCED) {
        result = scaleImage(src, targetWidth, targetHeight, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    } else if (scalingMethod == Scalr.Method.QUALITY) {
        /*
			 * If we are scaling up (in either width or height - since we know
			 * the image will stay proportional we just check if either are
			 * being scaled up), directly using a single BICUBIC will give us
			 * better results then using Chris Campbell's incremental scaling
			 * operation (and take a lot less time). If we are scaling down, we
			 * must use the incremental scaling algorithm for the best result.
			 */
        if (targetWidth > currentWidth || targetHeight > currentHeight) {
            log("\tQUALITY Up-scale, single BICUBIC scaling will be used...");
            /*
				 * BILINEAR and BICUBIC look similar the smaller the scale jump
				 * upwards is, if the scale is larger BICUBIC looks sharper and
				 * less fuzzy. But most importantly we have to use BICUBIC to
				 * match the contract of the QUALITY rendering method. This note
				 * is just here for anyone reading the code and wondering how
				 * they can speed their own calls up.
				 */
            result = scaleImage(src, targetWidth, targetHeight, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        } else {
            log("\tQUALITY Down-scale, incremental scaling will be used...");
            /*
				 * Originally we wanted to use BILINEAR interpolation here
				 * because it takes 1/3rd the time that the BICUBIC
				 * interpolation does, however, when scaling large images down
				 * to most sizes bigger than a thumbnail we witnessed noticeable
				 * "softening" in the resultant image with BILINEAR that would
				 * be unexpectedly annoying to a user expecting a "QUALITY"
				 * scale of their original image. Instead BICUBIC was chosen to
				 * honor the contract of a QUALITY scale of the original image.
				 */
            result = scaleImageIncrementally(src, targetWidth, targetHeight, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        }
    }
    // Apply the image ops if any were provided
    if (ops != null && ops.length > 0) {
        if (DEBUG)
            log("Applying %d Image Ops to Result", ops.length);
        for (BufferedImageOp op : ops) {
            // In case a null op was passed in, skip it instead of dying
            if (op == null)
                continue;
            long opStartTime = System.currentTimeMillis();
            Rectangle2D dims = op.getBounds2D(result);
            /*
				 * We must manually create the target image; we cannot rely on
				 * the null-dest filter() method to create a valid destination
				 * for us thanks to this JDK bug that has been filed for almost
				 * a decade:
				 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606
				 */
            BufferedImage dest = new BufferedImage((int) Math.round(dims.getWidth()), (int) Math.round(dims.getHeight()), result.getType());
            result = op.filter(result, dest);
            if (DEBUG)
                log("\tOp Applied in %d ms, Resultant Image [width=%d, height=%d], Op: %s", (System.currentTimeMillis() - opStartTime), result.getWidth(), result.getHeight(), op);
        }
    }
    // Perform the rotation if one was requested
    if (rotation != Rotation.NONE) {
        if (DEBUG)
            log("Applying %s rotation to image...", rotation);
        long rotStartTime = System.currentTimeMillis();
        /*
			 * A 90 or -90 degree rotation will cause the height and width to
			 * flip-flop from the original image to the rotated one.
			 *
			 * Given that MOST rotations will typically be some form of a
			 * 90-degree rotation (portrait to landscape, etc.) just assume that
			 * here and correct it below in the switch statement if need be.
			 */
        int newWidth = result.getHeight();
        int newHeight = result.getWidth();
        /*
			 * We create a transform per operation request as (oddly enough) it
			 * ends up being faster for the VM to create, use and destroy these
			 * instances than it is to re-use a single AffineTransform
			 * per-thread via the AffineTransform.setTo(...) methods which was
			 * my first choice (less object creation).
			 *
			 * Unfortunately this introduces the need for ThreadLocal instances
			 * of AffineTransforms to avoid race conditions where two or more
			 * resize threads are manipulating the same transform before
			 * applying it.
			 *
			 * ThreadLocals are one of the #1 reasons for memory leaks in server
			 * applications and since we have no nice way to hook into the
			 * init/destroy Servlet cycle or any other initialization cycle for
			 * this library to automatically call ThreadLocal.remove() to avoid
			 * the memory leak, it would have made using this library *safely*
			 * on the server side much harder.
			 *
			 * So we opt for creating individual transforms per rotation op and
			 * let the VM clean them up in a GC.
			 */
        AffineTransform tx = new AffineTransform();
        switch(rotation) {
            case CLOCKWISE:
                // Reminder: newWidth == result.getHeight() at this point
                tx.translate(newWidth, 0);
                tx.rotate(Math.toRadians(90));
                break;
            case COUNTER_CLOCKWISE:
                // Reminder: newHeight == result.getWidth() at this point
                tx.translate(0, newHeight);
                tx.rotate(Math.toRadians(-90));
                break;
            case FLIP:
                /*
				 * This is the one rotation case where the new width and height
				 * will be the same as the original image, so reset the values
				 * from the defaults we set above.
				 */
                newWidth = result.getWidth();
                newHeight = result.getHeight();
                tx.translate(newWidth, newHeight);
                tx.rotate(Math.toRadians(180));
                break;
        }
        /*
			 * Create our target image we will render the rotated result to. At
			 * this point the resultant image has already been put into the best
			 * image type so we can just copy that without trying to
			 * re-determine the most effective image type like scaleImage(...)
			 * has to do.
			 */
        BufferedImage rotatedImage = new BufferedImage(newWidth, newHeight, result.getType());
        Graphics2D g2d = (Graphics2D) rotatedImage.createGraphics();
        /*
			 * Render the resultant image to our new rotatedImage buffer,
			 * applying the AffineTransform that we calculated above during
			 * rendering so the pixels from the old position to the new
			 * transposed positions are mapped correctly.
			 */
        g2d.drawImage(result, tx, null);
        g2d.dispose();
        /*
			 * Before re-assigning the new result to be returned to our rotated
			 * image, explicitly notify the VM that you are done with any
			 * resources being used by the old resultant image that we don't
			 * need anymore.
			 */
        result.flush();
        // Reassign the result to our rotated image before returning it.
        result = rotatedImage;
        if (DEBUG)
            log("\t%s Rotation Applied in %d ms, Resultant Image [width=%d, height=%d]", rotation, (System.currentTimeMillis() - rotStartTime), result.getWidth(), result.getHeight());
    }
    if (DEBUG) {
        long elapsedTime = System.currentTimeMillis() - startTime;
        log("END Source Image Scaled from [%dx%d] to [%dx%d] and %d BufferedImageOp(s) Applied in %d ms", currentWidth, currentHeight, result.getWidth(), result.getHeight(), (ops == null ? 0 : ops.length), elapsedTime);
    }
    return result;
}
Example 71
Project: geotoolkit-master  File: MosaicImageWriter.java View source code
/**
     * Gets and initializes an {@linkplain ImageReader image reader} that can decode the
     * {@linkplain BufferedImageOp#filter filtered} input. The returned reader has its
     * {@linkplain ImageReader#setInput input} already set. If the reader input is different than
     * the specified one, then it is probably an {@linkplain ImageInputStream image input stream}
     * and closing it is caller's responsibility.
     *
     * @param  input The input to read.
     * @param  inputIndex The image index to read from the given input file.
     * @param  The parameters given by the user, or {@code null} if none.
     * @return The image reader that seems to be the most appropriated (never {@code null}).
     * @throws IOException If no suitable image reader has been found or if an error occurred
     *         while creating an image reader or initializing it.
     */
private ImageReader getImageReader(final Object input, final int inputIndex, final ImageWriteParam parameters) throws IOException {
    BufferedImageOp op = null;
    final ImageReader reader = getImageReader(input);
    if (parameters instanceof MosaicImageWriteParam) {
        final MosaicImageWriteParam param = (MosaicImageWriteParam) parameters;
        if (param.getTileWritingPolicy() == TileWritingPolicy.NO_WRITE) {
            return reader;
        }
        op = param.getSourceTileFilter();
    }
    /*
         * If we are allowed to cache an uncompressed copies of the tiles, do that now.
         */
    if (op != null || isCachingEnabled(reader, inputIndex)) {
        final Collection<Tile> tiles = new ArrayList<>();
        if (reader instanceof MosaicImageReader) {
            for (final TileManager manager : ((MosaicImageReader) reader).getInput()) {
                tiles.addAll(manager.getTiles());
            }
        } else {
            // Note: we must not use reader.getInput() since it may be an ImageInputStream.
            tiles.add(new Tile(reader.getOriginatingProvider(), input, 0, new Point(), (Dimension) null));
        }
    /*
             * TODO: Folllowing has been disabled for now because the whole org.geotoolkit.internal.rmi package
             *       has been removed. This is because JDK8 provides a new "fork join" framework make our stuff
             *       obsolete (but we didn't migrated to JDK8 yet). The plan is to rewrite the functionality
             *       from scratch in the Apache SIS project. Since the temporary files are optional, disabling
             *       this code should not break the application. It may make it much slower, but we had issues
             *       with the RAW format used by this code anyway.
             */
    //          temporaryFiles.putAll(RMI.execute(new TileCopier(tiles, op)));
    }
    return reader;
}
Example 72
Project: imgscalr-master  File: Scalr.java View source code
/**
	 * Used to apply, in the order given, 1 or more {@link BufferedImageOp}s to
	 * a given {@link BufferedImage} and return the result.
	 * <p/>
	 * <strong>Feature</strong>: This implementation works around <a
	 * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606">a
	 * decade-old JDK bug</a> that can cause a {@link RasterFormatException}
	 * when applying a perfectly valid {@link BufferedImageOp}s to images.
	 * <p/>
	 * <strong>Feature</strong>: This implementation also works around
	 * {@link BufferedImageOp}s failing to apply and throwing
	 * {@link ImagingOpException}s when run against a <code>src</code> image
	 * type that is poorly supported. Unfortunately using {@link ImageIO} and
	 * standard Java methods to load images provides no consistency in getting
	 * images in well-supported formats. This method automatically accounts and
	 * corrects for all those problems (if necessary).
	 * <p/>
	 * It is recommended you always use this method to apply any
	 * {@link BufferedImageOp}s instead of relying on directly using the
	 * {@link BufferedImageOp#filter(BufferedImage, BufferedImage)} method.
	 * <p/>
	 * <strong>Performance</strong>: Not all {@link BufferedImageOp}s are
	 * hardware accelerated operations, but many of the most popular (like
	 * {@link ConvolveOp}) are. For more information on if your image op is
	 * hardware accelerated or not, check the source code of the underlying JDK
	 * class that actually executes the Op code, <a href=
	 * "http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html"
	 * >sun.awt.image.ImagingLib</a>.
	 * <p/>
	 * <strong>TIP</strong>: This operation leaves the original <code>src</code>
	 * image unmodified. If the caller is done with the <code>src</code> image
	 * after getting the result of this operation, remember to call
	 * {@link BufferedImage#flush()} on the <code>src</code> to free up native
	 * resources and make it easier for the GC to collect the unused image.
	 * 
	 * @param src
	 *            The image that will have the ops applied to it.
	 * @param ops
	 *            <code>1</code> or more ops to apply to the image.
	 * 
	 * @return a new {@link BufferedImage} that represents the <code>src</code>
	 *         with all the given operations applied to it.
	 * 
	 * @throws IllegalArgumentException
	 *             if <code>src</code> is <code>null</code>.
	 * @throws IllegalArgumentException
	 *             if <code>ops</code> is <code>null</code> or empty.
	 * @throws ImagingOpException
	 *             if one of the given {@link BufferedImageOp}s fails to apply.
	 *             These exceptions bubble up from the inside of most of the
	 *             {@link BufferedImageOp} implementations and are explicitly
	 *             defined on the imgscalr API to make it easier for callers to
	 *             catch the exception (if they are passing along optional ops
	 *             to be applied). imgscalr takes detailed steps to avoid the
	 *             most common pitfalls that will cause {@link BufferedImageOp}s
	 *             to fail, even when using straight forward JDK-image
	 *             operations.
	 */
public static BufferedImage apply(BufferedImage src, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException {
    long t = -1;
    if (DEBUG)
        t = System.currentTimeMillis();
    if (src == null)
        throw new IllegalArgumentException("src cannot be null");
    if (ops == null || ops.length == 0)
        throw new IllegalArgumentException("ops cannot be null or empty");
    int type = src.getType();
    /*
		 * Ensure the src image is in the best supported image type before we
		 * continue, otherwise it is possible our calls below to getBounds2D and
		 * certainly filter(...) may fail if not.
		 * 
		 * Java2D makes an attempt at applying most BufferedImageOps using
		 * hardware acceleration via the ImagingLib internal library.
		 * 
		 * Unfortunately may of the BufferedImageOp are written to simply fail
		 * with an ImagingOpException if the operation cannot be applied with no
		 * additional information about what went wrong or attempts at
		 * re-applying it in different ways.
		 * 
		 * This is assuming the failing BufferedImageOp even returns a null
		 * image after failing to apply; some simply return a corrupted/black
		 * image that result in no exception and it is up to the user to
		 * discover this.
		 * 
		 * In internal testing, EVERY failure I've ever seen was the result of
		 * the source image being in a poorly-supported BufferedImage Type like
		 * BGR or ABGR (even though it was loaded with ImageIO).
		 * 
		 * To avoid this nasty/stupid surprise with BufferedImageOps, we always
		 * ensure that the src image starts in an optimally supported format
		 * before we try and apply the filter.
		 */
    if (!(type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB))
        src = copyToOptimalImage(src);
    if (DEBUG)
        log(0, "Applying %d BufferedImageOps...", ops.length);
    boolean hasReassignedSrc = false;
    for (int i = 0; i < ops.length; i++) {
        long subT = -1;
        if (DEBUG)
            subT = System.currentTimeMillis();
        BufferedImageOp op = ops[i];
        // Skip null ops instead of throwing an exception.
        if (op == null)
            continue;
        if (DEBUG)
            log(1, "Applying BufferedImageOp [class=%s, toString=%s]...", op.getClass(), op.toString());
        /*
			 * Must use op.getBounds instead of src.getWidth and src.getHeight
			 * because we are trying to create an image big enough to hold the
			 * result of this operation (which may be to scale the image
			 * smaller), in that case the bounds reported by this op and the
			 * bounds reported by the source image will be different.
			 */
        Rectangle2D resultBounds = op.getBounds2D(src);
        // Watch out for flaky/misbehaving ops that fail to work right.
        if (resultBounds == null)
            throw new ImagingOpException("BufferedImageOp [" + op.toString() + "] getBounds2D(src) returned null bounds for the target image; this should not happen and indicates a problem with application of this type of op.");
        /*
			 * We must manually create the target image; we cannot rely on the
			 * null-destination filter() method to create a valid destination
			 * for us thanks to this JDK bug that has been filed for almost a
			 * decade:
			 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606
			 */
        BufferedImage dest = createOptimalImage(src, (int) Math.round(resultBounds.getWidth()), (int) Math.round(resultBounds.getHeight()));
        // Perform the operation, update our result to return.
        BufferedImage result = op.filter(src, dest);
        /*
			 * Flush the 'src' image ONLY IF it is one of our interim temporary
			 * images being used when applying 2 or more operations back to
			 * back. We never want to flush the original image passed in.
			 */
        if (hasReassignedSrc)
            src.flush();
        /*
			 * Incase there are more operations to perform, update what we
			 * consider the 'src' reference to our last result so on the next
			 * iteration the next op is applied to this result and not back
			 * against the original src passed in.
			 */
        src = result;
        /*
			 * Keep track of when we re-assign 'src' to an interim temporary
			 * image, so we know when we can explicitly flush it and clean up
			 * references on future iterations.
			 */
        hasReassignedSrc = true;
        if (DEBUG)
            log(1, "Applied BufferedImageOp in %d ms, result [width=%d, height=%d]", System.currentTimeMillis() - subT, result.getWidth(), result.getHeight());
    }
    if (DEBUG)
        log(0, "All %d BufferedImageOps applied in %d ms", ops.length, System.currentTimeMillis() - t);
    return src;
}
Example 73
Project: intellij-community-master  File: UIUtil.java View source code
public static void drawImage(Graphics g, BufferedImage image, BufferedImageOp op, int x, int y) {
    if (image instanceof JBHiDPIScaledImage) {
        Image img = ((JBHiDPIScaledImage) image).getDelegate();
        if (img == null) {
            img = image;
        }
        if (op != null && img instanceof BufferedImage)
            img = op.filter((BufferedImage) img, null);
        int dstw = ImageUtil.getUserWidth(image);
        int dsth = ImageUtil.getUserHeight(image);
        int srcw = ImageUtil.getRealWidth(image);
        int srch = ImageUtil.getRealHeight(image);
        g.drawImage(img, x, y, x + dstw, y + dsth, 0, 0, srcw, srch, null);
    } else {
        ((Graphics2D) g).drawImage(image, op, x, y);
    }
}
Example 74
Project: li-old-master  File: Scalr.java View source code
/**
     * Used to apply, in the order given, 1 or more {@link BufferedImageOp}s to a given {@link BufferedImage} and return the result.
     * <p/>
     * <strong>Feature</strong>: This implementation works around <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606">a decade-old JDK bug</a> that can cause a {@link RasterFormatException} when applying a perfectly valid {@link BufferedImageOp}s to images.
     * <p/>
     * <strong>Feature</strong>: This implementation also works around {@link BufferedImageOp}s failing to apply and throwing {@link ImagingOpException}s when run against a <code>src</code> image type that is poorly supported. Unfortunately using {@link ImageIO} and standard Java methods to load images provides no consistency in getting images in well-supported formats. This method automatically accounts and corrects for all those problems (if necessary).
     * <p/>
     * It is recommended you always use this method to apply any {@link BufferedImageOp}s instead of relying on directly using the {@link BufferedImageOp#filter(BufferedImage, BufferedImage)} method.
     * <p/>
     * <strong>Performance</strong>: Not all {@link BufferedImageOp}s are hardware accelerated operations, but many of the most popular (like {@link ConvolveOp}) are. For more information on if your image op is hardware accelerated or not, check the source code of the underlying JDK class that actually executes the Op code, <a href= "http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html" >sun.awt.image.ImagingLib</a>.
     * <p/>
     * <strong>TIP</strong>: This operation leaves the original <code>src</code> image unmodified. If the caller is done with the <code>src</code> image after getting the result of this operation, remember to call {@link BufferedImage#flush()} on the <code>src</code> to free up native resources and make it easier for the GC to collect the unused image.
     * 
     * @param src The image that will have the ops applied to it.
     * @param ops <code>1</code> or more ops to apply to the image.
     * @return a new {@link BufferedImage} that represents the <code>src</code> with all the given operations applied to it.
     * @throws IllegalArgumentException if <code>src</code> is <code>null</code>.
     * @throws IllegalArgumentException if <code>ops</code> is <code>null</code> or empty.
     * @throws ImagingOpException if one of the given {@link BufferedImageOp}s fails to apply. These exceptions bubble up from the inside of most of the {@link BufferedImageOp} implementations and are explicitly defined on the imgscalr API to make it easier for callers to catch the exception (if they are passing along optional ops to be applied). imgscalr takes detailed steps to avoid the most common pitfalls that will cause {@link BufferedImageOp}s to fail, even when using straight forward JDK-image operations.
     */
public static BufferedImage apply(BufferedImage src, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException {
    long t = System.currentTimeMillis();
    if (src == null)
        throw new IllegalArgumentException("src cannot be null");
    if (ops == null || ops.length == 0)
        throw new IllegalArgumentException("ops cannot be null or empty");
    int type = src.getType();
    /*
         * Ensure the src image is in the best supported image type before we continue, otherwise it is possible our calls below to getBounds2D and certainly filter(...) may fail if not. Java2D makes an attempt at applying most BufferedImageOps using hardware acceleration via the ImagingLib internal library. Unfortunately may of the BufferedImageOp are written to simply fail with an ImagingOpException if the operation cannot be applied with no additional information about what went wrong or attempts at re-applying it in different ways. This is assuming the failing BufferedImageOp even returns a null image after failing to apply; some simply return a corrupted/black image that result in no exception and it is up to the user to discover this. In internal testing, EVERY failure I've ever seen was the result of the source image being in a poorly-supported BufferedImage Type like BGR or ABGR (even though it was loaded with ImageIO). To avoid this nasty/stupid surprise with
         * BufferedImageOps, we always ensure that the src image starts in an optimally supported format before we try and apply the filter.
         */
    if (!(type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB))
        src = copyToOptimalImage(src);
    if (DEBUG)
        log(0, "Applying %d BufferedImageOps...", ops.length);
    boolean hasReassignedSrc = false;
    for (int i = 0; i < ops.length; i++) {
        long subT = System.currentTimeMillis();
        BufferedImageOp op = ops[i];
        // Skip null ops instead of throwing an exception.
        if (op == null)
            continue;
        if (DEBUG)
            log(1, "Applying BufferedImageOp [class=%s, toString=%s]...", op.getClass(), op.toString());
        /*
             * Must use op.getBounds instead of src.getWidth and src.getHeight because we are trying to create an image big enough to hold the result of this operation (which may be to scale the image smaller), in that case the bounds reported by this op and the bounds reported by the source image will be different.
             */
        Rectangle2D resultBounds = op.getBounds2D(src);
        // Watch out for flaky/misbehaving ops that fail to work right.
        if (resultBounds == null)
            throw new ImagingOpException("BufferedImageOp [" + op.toString() + "] getBounds2D(src) returned null bounds for the target image; this should not happen and indicates a problem with application of this type of op.");
        /*
             * We must manually create the target image; we cannot rely on the null-destination filter() method to create a valid destination for us thanks to this JDK bug that has been filed for almost a decade: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606
             */
        BufferedImage dest = createOptimalImage(src, (int) Math.round(resultBounds.getWidth()), (int) Math.round(resultBounds.getHeight()));
        // Perform the operation, update our result to return.
        BufferedImage result = op.filter(src, dest);
        /*
             * Flush the 'src' image ONLY IF it is one of our interim temporary images being used when applying 2 or more operations back to back. We never want to flush the original image passed in.
             */
        if (hasReassignedSrc)
            src.flush();
        /*
             * Incase there are more operations to perform, update what we consider the 'src' reference to our last result so on the next iteration the next op is applied to this result and not back against the original src passed in.
             */
        src = result;
        /*
             * Keep track of when we re-assign 'src' to an interim temporary image, so we know when we can explicitly flush it and clean up references on future iterations.
             */
        hasReassignedSrc = true;
        if (DEBUG)
            log(1, "Applied BufferedImageOp in %d ms, result [width=%d, height=%d]", System.currentTimeMillis() - subT, result.getWidth(), result.getHeight());
    }
    if (DEBUG)
        log(0, "All %d BufferedImageOps applied in %d ms", ops.length, System.currentTimeMillis() - t);
    return src;
}
Example 75
Project: play-scalr-master  File: Resizer.java View source code
/**
     * Used to apply, in the order given, 1 or more {@link BufferedImageOp}s to
     * a given {@link BufferedImage} and return the result.
     * <p/>
     * <strong>Feature</strong>: This implementation works around <a
     * href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606">a
     * decade-old JDK bug</a> that can cause a {@link RasterFormatException}
     * when applying a perfectly valid {@link BufferedImageOp}s to images.
     * <p/>
     * <strong>Feature</strong>: This implementation also works around
     * {@link BufferedImageOp}s failing to apply and throwing
     * {@link ImagingOpException}s when run against a <code>src</code> image
     * type that is poorly supported. Unfortunately using {@link ImageIO} and
     * standard Java methods to load images provides no consistency in getting
     * images in well-supported formats. This method automatically accounts and
     * corrects for all those problems (if necessary).
     * <p/>
     * It is recommended you always use this method to apply any
     * {@link BufferedImageOp}s instead of relying on directly using the
     * {@link BufferedImageOp#filter(BufferedImage, BufferedImage)} method.
     * <p/>
     * <strong>Performance</strong>: Not all {@link BufferedImageOp}s are
     * hardware accelerated operations, but many of the most popular (like
     * {@link ConvolveOp}) are. For more information on if your image op is
     * hardware accelerated or not, check the source code of the underlying JDK
     * class that actually executes the Op code, <a href=
     * "http://www.docjar.com/html/api/sun/awt/image/ImagingLib.java.html"
     * >sun.awt.image.ImagingLib</a>.
     * <p/>
     * <strong>TIP</strong>: This operation leaves the original <code>src</code>
     * image unmodified. If the caller is done with the <code>src</code> image
     * after getting the result of this operation, remember to call
     * {@link BufferedImage#flush()} on the <code>src</code> to free up native
     * resources and make it easier for the GC to collect the unused image.
     *
     * @param src
     *            The image that will have the ops applied to it.
     * @param ops
     *            <code>1</code> or more ops to apply to the image.
     *
     * @return a new {@link BufferedImage} that represents the <code>src</code>
     *         with all the given operations applied to it.
     *
     * @throws IllegalArgumentException
     *             if <code>src</code> is <code>null</code>.
     * @throws IllegalArgumentException
     *             if <code>ops</code> is <code>null</code> or empty.
     * @throws ImagingOpException
     *             if one of the given {@link BufferedImageOp}s fails to apply.
     *             These exceptions bubble up from the inside of most of the
     *             {@link BufferedImageOp} implementations and are explicitly
     *             defined on the imgscalr API to make it easier for callers to
     *             catch the exception (if they are passing along optional ops
     *             to be applied). imgscalr takes detailed steps to avoid the
     *             most common pitfalls that will cause {@link BufferedImageOp}s
     *             to fail, even when using straight forward JDK-image
     *             operations.
     */
public static BufferedImage apply(BufferedImage src, BufferedImageOp... ops) throws IllegalArgumentException, ImagingOpException {
    long t = System.currentTimeMillis();
    if (src == null)
        throw new IllegalArgumentException("src cannot be null");
    if (ops == null || ops.length == 0)
        throw new IllegalArgumentException("ops cannot be null or empty");
    int type = src.getType();
    /*
		 * Ensure the src image is in the best supported image type before we
		 * continue, otherwise it is possible our calls below to getBounds2D and
		 * certainly filter(...) may fail if not.
		 *
		 * Java2D makes an attempt at applying most BufferedImageOps using
		 * hardware acceleration via the ImagingLib internal library.
		 *
		 * Unfortunately may of the BufferedImageOp are written to simply fail
		 * with an ImagingOpException if the operation cannot be applied with no
		 * additional information about what went wrong or attempts at
		 * re-applying it in different ways.
		 *
		 * This is assuming the failing BufferedImageOp even returns a null
		 * image after failing to apply; some simply return a corrupted/black
		 * image that result in no exception and it is up to the user to
		 * discover this.
		 *
		 * In internal testing, EVERY failure I've ever seen was the result of
		 * the source image being in a poorly-supported BufferedImage Type like
		 * BGR or ABGR (even though it was loaded with ImageIO).
		 *
		 * To avoid this nasty/stupid surprise with BufferedImageOps, we always
		 * ensure that the src image starts in an optimally supported format
		 * before we try and apply the filter.
		 */
    if (!(type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB))
        src = copyToOptimalImage(src);
    if (DEBUG)
        log(0, "Applying %d BufferedImageOps...", ops.length);
    boolean hasReassignedSrc = false;
    for (int i = 0; i < ops.length; i++) {
        long subT = System.currentTimeMillis();
        BufferedImageOp op = ops[i];
        // Skip null ops instead of throwing an exception.
        if (op == null)
            continue;
        if (DEBUG)
            log(1, "Applying BufferedImageOp [class=%s, toString=%s]...", op.getClass(), op.toString());
        /*
			 * Must use op.getBounds instead of src.getWidth and src.getHeight
			 * because we are trying to create an image big enough to hold the
			 * result of this operation (which may be to scale the image
			 * smaller), in that case the bounds reported by this op and the
			 * bounds reported by the source image will be different.
			 */
        Rectangle2D resultBounds = op.getBounds2D(src);
        // Watch out for flaky/misbehaving ops that fail to work right.
        if (resultBounds == null)
            throw new ImagingOpException("BufferedImageOp [" + op.toString() + "] getBounds2D(src) returned null bounds for the target image; this should not happen and indicates a problem with application of this type of op.");
        /*
			 * We must manually create the target image; we cannot rely on the
			 * null-destination filter() method to create a valid destination
			 * for us thanks to this JDK bug that has been filed for almost a
			 * decade:
			 * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606
			 */
        BufferedImage dest = createOptimalImage(src, (int) Math.round(resultBounds.getWidth()), (int) Math.round(resultBounds.getHeight()));
        // Perform the operation, update our result to return.
        BufferedImage result = op.filter(src, dest);
        /*
			 * Flush the 'src' image ONLY IF it is one of our interim temporary
			 * images being used when applying 2 or more operations back to
			 * back. We never want to flush the original image passed in.
			 */
        if (hasReassignedSrc)
            src.flush();
        /*
			 * Incase there are more operations to perform, update what we
			 * consider the 'src' reference to our last result so on the next
			 * iteration the next op is applied to this result and not back
			 * against the original src passed in.
			 */
        src = result;
        /*
			 * Keep track of when we re-assign 'src' to an interim temporary
			 * image, so we know when we can explicitly flush it and clean up
			 * references on future iterations.
			 */
        hasReassignedSrc = true;
        if (DEBUG)
            log(1, "Applied BufferedImageOp in %d ms, result [width=%d, height=%d]", System.currentTimeMillis() - subT, result.getWidth(), result.getHeight());
    }
    if (DEBUG)
        log(0, "All %d BufferedImageOps applied in %d ms", ops.length, System.currentTimeMillis() - t);
    return src;
}
Example 76
Project: WorldPainter-master  File: App.java View source code
DockableFrame build() {
    DockableFrame dockableFrame = new DockableFrame(id);
    JPanel panel = new JPanel(new GridBagLayout());
    if (margin > 0) {
        panel.setBorder(new EmptyBorder(margin, margin, margin, margin));
    }
    GridBagConstraints constraints = new GridBagConstraints();
    constraints.gridwidth = GridBagConstraints.REMAINDER;
    constraints.weightx = 1.0;
    if (expand) {
        constraints.fill = GridBagConstraints.BOTH;
        constraints.weighty = 1.0;
        panel.add(component, constraints);
    } else {
        constraints.fill = GridBagConstraints.HORIZONTAL;
        panel.add(component, constraints);
        constraints.weighty = 1.0;
        panel.add(new JPanel(), constraints);
    }
    dockableFrame.add(panel, BorderLayout.CENTER);
    // Use title everywhere
    dockableFrame.setTitle(title);
    dockableFrame.setSideTitle(title);
    dockableFrame.setTabTitle(title);
    dockableFrame.setToolTipText(title);
    // Try to find an icon to use for the tab
    if ((icon == null) && (component instanceof Container)) {
        icon = findIcon((Container) component);
        if (icon != null) {
            if (((icon.getIconHeight() > 16 * UI_SCALE) || (icon.getIconWidth() > 16 * UI_SCALE)) && (icon instanceof ImageIcon) && (((ImageIcon) icon).getImage() instanceof BufferedImage)) {
                float s;
                if (icon.getIconWidth() > icon.getIconHeight()) {
                    // Wide icon
                    s = 16f * UI_SCALE / icon.getIconWidth();
                } else {
                    // Tall (or square) icon
                    s = 16f * UI_SCALE / icon.getIconHeight();
                }
                BufferedImageOp op = new AffineTransformOp(AffineTransform.getScaleInstance(s, s), AffineTransformOp.TYPE_BICUBIC);
                BufferedImage iconImage = op.filter((BufferedImage) ((ImageIcon) icon).getImage(), null);
                icon = new ImageIcon(iconImage);
            }
        }
    }
    dockableFrame.setFrameIcon(icon);
    // Use preferred size of component as much as possible
    final java.awt.Dimension preferredSize = component.getPreferredSize();
    dockableFrame.setAutohideWidth(preferredSize.width);
    dockableFrame.setDockedWidth(preferredSize.width);
    dockableFrame.setDockedHeight(preferredSize.height);
    dockableFrame.setUndockedBounds(new Rectangle(-1, -1, preferredSize.width, preferredSize.height));
    // Make hidable, but don't display hide button, so incidental panels can
    // be hidden on the fly
    dockableFrame.setHidable(true);
    dockableFrame.setAvailableButtons(BUTTON_FLOATING | BUTTON_AUTOHIDE | BUTTON_HIDE_AUTOHIDE);
    // Disable the context menu because it contains the Close option with no way to hide it
    dockableFrame.setShowContextMenu(false);
    // Initial location of panel
    dockableFrame.setInitMode(DockContext.STATE_FRAMEDOCKED);
    dockableFrame.setInitSide(side);
    dockableFrame.setInitIndex(index);
    // Other flags
    dockableFrame.setAutohideWhenActive(true);
    dockableFrame.setMaximizable(false);
    //Help key
    dockableFrame.putClientProperty(HELP_KEY_KEY, "Panel/" + id);
    return dockableFrame;
}
Example 77
Project: jcaptcha-trunk-master  File: ImageDeformationByBufferedImageOp.java View source code
public void setImageOperations(List<BufferedImageOp> imageOperations) {
    ImageOperations = imageOperations;
}
Example 78
Project: screenshot-master  File: BlurFilter.java View source code
@Override
public BufferedImage apply(BufferedImage image) {
    Kernel kernel = new Kernel(3, 3, new float[] { 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f, 1f / 9f });
    BufferedImageOp blurOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
    return blurOp.filter(image, null);
}
Example 79
Project: GdxStudio-master  File: FilterEffect.java View source code
public BufferedImageOp getFilter() {
    return filter;
}
Example 80
Project: GPVM-master  File: FilterEffect.java View source code
/**
	 * Get the filter being applied by this effect
	 * 
	 * @return The filter being applied by this effect
	 */
public BufferedImageOp getFilter() {
    return filter;
}
Example 81
Project: hale-master  File: NoopRefresher.java View source code
@Override
public void setImageOp(BufferedImageOp imageOp) {
// nothing to do here
}
Example 82
Project: java-image-processing-survival-guide-master  File: BufferedImageOperations.java View source code
public static BufferedImage apply(BufferedImage source, Collection<BufferedImageOp> bufferedImageOps) {
    BufferedImage result = source;
    for (BufferedImageOp bufferedImageOp : bufferedImageOps) {
        result = bufferedImageOp.filter(result, null);
    }
    return result;
}
Example 83
Project: jumpnevolve-master  File: FilterEffect.java View source code
/**
	 * Get the filter being applied by this effect
	 * 
	 * @return The filter being applied by this effect
	 */
public BufferedImageOp getFilter() {
    return filter;
}
Example 84
Project: libgdx-master  File: FilterEffect.java View source code
public BufferedImageOp getFilter() {
    return filter;
}
Example 85
Project: LuaWars-master  File: FilterEffect.java View source code
/**
	 * Get the filter being applied by this effect
	 * 
	 * @return The filter being applied by this effect
	 */
public BufferedImageOp getFilter() {
    return filter;
}
Example 86
Project: MyBomberman-master  File: FilterEffect.java View source code
/**
	 * Get the filter being applied by this effect
	 * 
	 * @return The filter being applied by this effect
	 */
public BufferedImageOp getFilter() {
    return filter;
}
Example 87
Project: ProjetX-master  File: FilterEffect.java View source code
/**
	 * Get the filter being applied by this effect
	 * 
	 * @return The filter being applied by this effect
	 */
public BufferedImageOp getFilter() {
    return filter;
}
Example 88
Project: SideScrollerGDW2012-Max-master  File: FilterEffect.java View source code
/**
	 * Get the filter being applied by this effect
	 * 
	 * @return The filter being applied by this effect
	 */
public BufferedImageOp getFilter() {
    return filter;
}
Example 89
Project: touhou-java-master  File: FilterEffect.java View source code
public BufferedImageOp getFilter() {
    return filter;
}
Example 90
Project: autopsy-master  File: ScalrWrapper.java View source code
public static synchronized BufferedImage cropImage(BufferedImage input, int width, int height) {
    return Scalr.crop(input, width, height, (BufferedImageOp) null);
}
Example 91
Project: ikvm-monotouch-master  File: ImagingLib.java View source code
public static BufferedImage filter(BufferedImageOp op, BufferedImage src, BufferedImage dst) {
    return null;
}
Example 92
Project: IKVM.NET-cvs-clone-master  File: ImagingLib.java View source code
public static BufferedImage filter(BufferedImageOp op, BufferedImage src, BufferedImage dst) {
    return null;
}
Example 93
Project: netention-old1-master  File: Icons.java View source code
public static BufferedImage convertToGrayscale(BufferedImage source) {
    BufferedImageOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
    return op.filter(source, null);
}
Example 94
Project: tomighty-master  File: Canvas.java View source code
public void applyFilter(BufferedImageOp filter) {
    image = filter.filter(image, image);
}
Example 95
Project: jnode-master  File: AbstractSurfaceGraphics.java View source code
/**
     * @param image
     * @param op
     * @param x
     * @param y
     * @see java.awt.Graphics2D#drawImage(java.awt.image.BufferedImage, java.awt.image.BufferedImageOp, int, int)
     */
public final void drawImage(BufferedImage image, BufferedImageOp op, int x, int y) {
    final BufferedImage dstImage = op.createCompatibleDestImage(image, surface.getColorModel());
    drawImage(op.filter(image, dstImage), x, y, null);
}
Example 96
Project: ascension-log-visualizer-new-master  File: AnimatedPanel.java View source code
/**
     * Changes the image luminosity.
     */
void setBrightness(final float multiple) {
    final float[] brightKernel = { multiple };
    final BufferedImageOp bright = new ConvolveOp(new Kernel(1, 1, brightKernel), ConvolveOp.EDGE_NO_OP, this.brightnessHints);
    bright.filter(this.originalImage, this.convolvedImage);
    this.repaint();
}
Example 97
Project: ConnectionViewer-master  File: EmptyGraphics2D.java View source code
@Override
public void drawImage(BufferedImage bi, BufferedImageOp bio, int i, int i1) {
}
Example 98
Project: josm-master  File: FakeGraphics.java View source code
@Override
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
}
Example 99
Project: montagnesdor-master  File: DummyGraphics2D.java View source code
@Override
public final void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
}
Example 100
Project: org.openscada.external-master  File: DummyGraphics2D.java View source code
@Override
public final void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
}
Example 101
Project: jajuk-master  File: TestJScrollingText.java View source code
/* (non-Javadoc)
     * @see java.awt.Graphics2D#drawImage(java.awt.image.BufferedImage, java.awt.image.BufferedImageOp, int, int)
     */
@Override
public void drawImage(BufferedImage img, BufferedImageOp op, int x, int y) {
}