Example usage for java.awt Graphics2D dispose

List of usage examples for java.awt Graphics2D dispose

Introduction

In this page you can find the example usage for java.awt Graphics2D dispose.

Prototype

public abstract void dispose();

Source Link

Document

Disposes of this graphics context and releases any system resources that it is using.

Usage

From source file:com.springsecurity.plugin.util.ImageResizer.java

public BufferedImage scale(File icon, int targetWidth, int targetHeight) {
    BufferedImage ret = null;//  w w w. j a  v  a 2 s. c  om
    if (icon.exists()) {
        try {
            BufferedImage img = ImageIO.read(icon);
            ret = img;
            int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
                    : BufferedImage.TYPE_INT_ARGB;
            BufferedImage scratchImage = null;
            Graphics2D g2 = null;
            int w = img.getWidth();
            int h = img.getHeight();
            int prevW = w;
            int prevH = h;
            do {
                if (w > targetWidth) {
                    w /= 2;
                    w = (w < targetWidth) ? targetWidth : w;
                }
                if (h > targetHeight) {
                    h /= 2;
                    h = (h < targetHeight) ? targetHeight : h;
                }
                if (scratchImage == null) {
                    scratchImage = new BufferedImage(w, h, type);
                    g2 = scratchImage.createGraphics();
                }

                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(ret, 0, 0, w, h, 0, 0, prevW, prevH, null);

                prevW = w;
                prevH = h;
                ret = scratchImage;
            } while (w != targetWidth || h != targetHeight);
            if (g2 != null) {
                g2.dispose();
            }
            if (targetWidth != ret.getWidth() || targetHeight != ret.getHeight()) {
                scratchImage = new BufferedImage(targetWidth, targetHeight, type);
                g2 = scratchImage.createGraphics();
                g2.drawImage(ret, 0, 0, null);
                g2.dispose();
                ret = scratchImage;
            }
        } catch (IOException e) {
        }
    }
    return ret;
}

From source file:net.sf.jasperreports.swing.JRViewerPanel.java

protected Image getPageErrorImage() {
    PrintPageFormat pageFormat = viewerContext.getPageFormat();
    Image image = new BufferedImage((int) (pageFormat.getPageWidth() * realZoom) + 1,
            (int) (pageFormat.getPageHeight() * realZoom) + 1, BufferedImage.TYPE_INT_RGB);

    AffineTransform transform = new AffineTransform();
    transform.scale(realZoom, realZoom);

    Graphics2D grx = (Graphics2D) image.getGraphics();
    try {/* w  w w.  j av  a 2  s.c  o  m*/
        grx.transform(transform);

        drawPageError(grx);
    } finally {
        grx.dispose();
    }

    return image;
}

From source file:net.rptools.maptool.client.MapTool.java

public static BufferedImage takeMapScreenShot(final PlayerView view) {
    final ZoneRenderer renderer = clientFrame.getCurrentZoneRenderer();
    if (renderer == null) {
        return null;
    }/* www . java 2 s .c  o  m*/

    Dimension size = renderer.getSize();
    if (size.width == 0 || size.height == 0) {
        return null;
    }

    BufferedImage image = new BufferedImage(size.width, size.height, Transparency.OPAQUE);
    final Graphics2D g = image.createGraphics();
    g.setClip(0, 0, size.width, size.height);

    // Have to do this on the EDT so that there aren't any odd side effects
    // of rendering
    // using a renderer that's on screen
    if (!EventQueue.isDispatchThread()) {
        try {
            EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    renderer.renderZone(g, view);
                }
            });
        } catch (InterruptedException ie) {
            MapTool.showError("While creating snapshot", ie);
        } catch (InvocationTargetException ite) {
            MapTool.showError("While creating snapshot", ite);
        }
    } else {
        renderer.renderZone(g, view);
    }

    g.dispose();

    return image;
}

From source file:edu.umn.cs.spatialHadoop.operations.GeometricPlot.java

/**
 * Draws an image that can be used as a scale for heat maps generated using
 * Plot or PlotPyramid.//from  www  .j a  v a 2 s. c  om
 * @param output - Output path
 * @param valueRange - Range of values of interest
 * @param width - Width of the generated image
 * @param height - Height of the generated image
 * @throws IOException
 */
public static void drawScale(Path output, MinMax valueRange, int width, int height) throws IOException {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = image.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, width, height);

    // fix this part to work according to color1, color2 and gradient type
    for (int y = 0; y < height; y++) {
        Color color = NASARectangle.calculateColor(y);
        g.setColor(color);
        g.drawRect(width * 3 / 4, y, width / 4, 1);
    }

    int fontSize = 24;
    g.setFont(new Font("Arial", Font.BOLD, fontSize));
    int step = (valueRange.maxValue - valueRange.minValue) * fontSize * 10 / height;
    step = (int) Math.pow(10, Math.round(Math.log10(step)));
    int min_value = valueRange.minValue / step * step;
    int max_value = valueRange.maxValue / step * step;

    for (int value = min_value; value <= max_value; value += step) {
        int y = fontSize + (height - fontSize)
                - value * (height - fontSize) / (valueRange.maxValue - valueRange.minValue);
        g.setColor(Color.WHITE);
        g.drawString(String.valueOf(value), 5, y);
    }

    g.dispose();

    FileSystem fs = output.getFileSystem(new Configuration());
    FSDataOutputStream outStream = fs.create(output, true);
    ImageIO.write(image, "png", outStream);
    outStream.close();
}

From source file:GifDecoder.java

/**
 * Creates new frame image from current data (and previous
 * frames as specified by their disposition codes).
 *//*from  ww w . j  a  v  a2  s .  co m*/
protected void setPixels() {
    // expose destination image's pixels as int array
    int[] dest = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();

    // fill in starting image contents based on last image's dispose code
    if (lastDispose > 0) {
        if (lastDispose == 3) {
            // use image before last
            int n = frameCount - 2;
            if (n > 0) {
                lastImage = getFrame(n - 1);
            } else {
                lastImage = null;
            }
        }

        if (lastImage != null) {
            int[] prev = ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData();
            System.arraycopy(prev, 0, dest, 0, width * height);
            // copy pixels

            if (lastDispose == 2) {
                // fill last image rect area with background color
                Graphics2D g = image.createGraphics();
                Color c = null;
                if (transparency) {
                    c = new Color(0, 0, 0, 0); // assume background is transparent
                } else {
                    c = new Color(lastBgColor); // use given background color
                }
                g.setColor(c);
                g.setComposite(AlphaComposite.Src); // replace area
                g.fill(lastRect);
                g.dispose();
            }
        }
    }

    // copy each source line to the appropriate place in the destination
    int pass = 1;
    int inc = 8;
    int iline = 0;
    for (int i = 0; i < ih; i++) {
        int line = i;
        if (interlace) {
            if (iline >= ih) {
                pass++;
                switch (pass) {
                case 2:
                    iline = 4;
                    break;
                case 3:
                    iline = 2;
                    inc = 4;
                    break;
                case 4:
                    iline = 1;
                    inc = 2;
                }
            }
            line = iline;
            iline += inc;
        }
        line += iy;
        if (line < height) {
            int k = line * width;
            int dx = k + ix; // start of line in dest
            int dlim = dx + iw; // end of dest line
            if ((k + width) < dlim) {
                dlim = k + width; // past dest edge
            }
            int sx = i * iw; // start of line in source
            while (dx < dlim) {
                // map color and insert in destination
                int index = ((int) pixels[sx++]) & 0xff;
                int c = act[index];
                if (c != 0) {
                    dest[dx] = c;
                }
                dx++;
            }
        }
    }
}

From source file:com.itextpdf.text.pdf.pdfcleanup.PdfCleanUpRenderListener.java

private void cleanImage(BufferedImage image, List<Rectangle> areasToBeCleaned) {
    Graphics2D graphics = image.createGraphics();
    graphics.setColor(CLEANED_AREA_FILL_COLOR);

    // A rectangle in the areasToBeCleaned list is treated to be in standard [0, 1]x[0,1] image space
    // (y varies from bottom to top and x from left to right), so we should scale the rectangle and also
    // invert and shear the y axe
    for (Rectangle rect : areasToBeCleaned) {
        int scaledBottomY = (int) Math.ceil(rect.getBottom() * image.getHeight());
        int scaledTopY = (int) Math.floor(rect.getTop() * image.getHeight());

        int x = (int) Math.ceil(rect.getLeft() * image.getWidth());
        int y = scaledTopY * -1 + image.getHeight();
        int width = (int) Math.floor(rect.getRight() * image.getWidth()) - x;
        int height = scaledTopY - scaledBottomY;

        graphics.fillRect(x, y, width, height);
    }//from  w  w  w .  j  a  v  a2s .co m

    graphics.dispose();
}

From source file:edu.ku.brc.specify.utilapps.sp5utils.Sp5Forms.java

public void generate() {
    BufferedImage bufImage = null;
    if (formFrame != null) {
        Component topComp = formFrame.getContentPane();

        Rectangle rect = topComp.getBounds();
        if (rect.width < 1 || rect.height < 1) {
            System.err.println("Can't create image. " + selectedForm.getTitle());
        } else {/*from   w  w  w . j  av  a  2 s  .  c  o m*/
            bufImage = new BufferedImage(rect.width, rect.height, (BufferedImage.TYPE_INT_ARGB));
            Graphics2D g2 = bufImage.createGraphics();
            topComp.paint(g2);
            g2.dispose();
        }
    }

    if (formIndex < forms.size()) {
        selectedForm = forms.get(formIndex);

        showForm();

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        formFrame.pack();
                        formFrame.repaint();
                    }
                });
            }
        });
    }

    File dir = new File("conversions" + File.separator + namePair.second + "_6" + File.separator + "forms");
    if (!dir.exists()) {
        dir.mkdirs();
    }

    if (bufImage != null) {
        String fName = dir.getAbsolutePath() + File.separator + formName + ".png";
        try {
            File imgFile = new File(fName);
            ImageIO.write(bufImage, "PNG", imgFile);

        } catch (Exception e) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ERDVisualizer.class, e);
            e.printStackTrace();
        }
    }

    if (formIndex >= forms.size()) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        if (formFrame != null)
                            formFrame.setVisible(false);
                        createIndex();
                        UIRegistry.showLocalizedMsg("Done");
                    }
                });
            }
        });
    }

    if (selectedForm != null) {
        formName = selectedForm.getFileName();
    }
}

From source file:com.neophob.sematrix.generator.Textwriter.java

/**
 * create image./*  w ww  .  j  a  v a  2 s  .  c om*/
 *
 * @param text the text
 */
public void createTextImage(String text) {
    //only load if needed
    if (StringUtils.equals(text, this.text)) {
        return;
    }

    this.text = text;

    BufferedImage img = new BufferedImage(TEXT_BUFFER_X_SIZE, internalBufferYSize, BufferedImage.TYPE_INT_RGB);

    Graphics2D g2 = img.createGraphics();
    FontRenderContext frc = g2.getFontRenderContext();
    TextLayout layout = new TextLayout(text, font, frc);
    Rectangle2D rect = layout.getBounds();

    int h = (int) (0.5f + rect.getHeight());
    maxXPos = (int) (0.5f + rect.getWidth()) + 5;
    ypos = internalBufferYSize - (internalBufferYSize - h) / 2;

    img = new BufferedImage(maxXPos, internalBufferYSize, BufferedImage.TYPE_INT_RGB);
    g2 = img.createGraphics();

    g2.setColor(color);
    g2.setFont(font);
    g2.setClip(0, 0, maxXPos, internalBufferYSize);
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);

    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g2.drawString(text, xpos, ypos);
    DataBufferInt dbi = (DataBufferInt) img.getRaster().getDataBuffer();
    textBuffer = dbi.getData();
    g2.dispose();

    wait = 0;
    xofs = 0;
    scrollRight = false;
}

From source file:com.imag.nespros.gui.plugin.GraphEditor.java

/**
 * create an instance of a simple graph with popup controls to create a
 * graph.//w  w w.  j a v a  2  s . co  m
 *
 */
private GraphEditor(Simulation s) {
    simu = s;
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        Logger.getLogger(GraphEditor.class.getName()).log(Level.SEVERE, null, ex);
    }
    // create a simple graph for the demo
    graph = Topology.getInstance().getGraph();
    this.layout = new StaticLayout<Device, ComLink>(graph, new Transformer<Device, Point2D>() {
        @Override
        public Point2D transform(Device v) {
            Point2D p = new Point2D.Double(v.getX(), v.getY());
            return p;
        }
    }, new Dimension(600, 600));

    vv = new VisualizationViewer<Device, ComLink>(layout);
    vv.setBackground(Color.white);

    final Transformer<Device, String> vertexLabelTransformer = new Transformer<Device, String>() {
        @Override
        public String transform(Device d) {
            return d.getDeviceName();
        }
    };

    //vv.getRenderContext().setVertexLabelTransformer(MapTransformer.<Device, String>getInstance(
    //      LazyMap.<Device, String>decorate(new HashMap<Device, String>(), new ToStringLabeller<Device>())));
    vv.getRenderContext().setVertexLabelTransformer(vertexLabelTransformer);
    vv.getRenderContext().setEdgeLabelTransformer(new Transformer<ComLink, String>() {
        @Override
        public String transform(ComLink link) {
            return (link.getID() + ", " + link.getLatency());
        }
    });
    //float dash[] = {0.1f};
    //final Stroke edgeStroke = new BasicStroke(3.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 1.0f);
    final Stroke edgeStroke = new BasicStroke(3.0f);
    final Transformer<ComLink, Stroke> edgeStrokeTransformer = new Transformer<ComLink, Stroke>() {
        @Override
        public Stroke transform(ComLink l) {
            return edgeStroke;
        }
    };
    Transformer<ComLink, Paint> edgePaint = new Transformer<ComLink, Paint>() {
        public Paint transform(ComLink l) {
            if (l.isDown()) {
                return Color.RED;
            } else {
                return Color.BLACK;
            }
        }
    };
    vv.getRenderContext().setEdgeDrawPaintTransformer(edgePaint);
    vv.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer);
    vv.setVertexToolTipTransformer(vv.getRenderContext().getVertexLabelTransformer());
    vv.getRenderContext().setVertexIconTransformer(new CustomVertexIconTransformer());
    vv.getRenderContext().setVertexShapeTransformer(new CustomVertexShapeTransformer());

    vv.addPreRenderPaintable(new VisualizationViewer.Paintable() {

        @Override
        public void paint(Graphics grphcs) {

            for (Device d : Topology.getInstance().getGraph().getVertices()) {
                int size = d.getOperators().size();
                MyLayeredIcon icon = d.getIcon();
                //if(icon == null) continue;
                icon.removeAll();
                if (size > 0) {
                    // the vertex icon                        
                    // Let's create the annotation image to be added to icon..
                    BufferedImage image = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB);
                    Graphics2D g = image.createGraphics();
                    g.setColor(Color.ORANGE);
                    g.fillOval(0, 0, 20, 20);
                    g.setColor(Color.BLACK);
                    g.drawString(size + "", 5, 13);
                    g.dispose();
                    ImageIcon img = new ImageIcon(image);
                    //Dimension id = new Dimension(icon.getIconWidth(), icon.getIconHeight());
                    //double x = vv.getModel().getGraphLayout().transform(d).getX();
                    //x -= (icon.getIconWidth() / 2);
                    //double y = vv.getModel().getGraphLayout().transform(d).getY();
                    //y -= (icon.getIconHeight() / 2);
                    //grphcs.drawImage(image, (int) Math.round(x), (int) Math.round(y), null);
                    icon.add(img);
                }
            }
        }

        @Override
        public boolean useTransform() {
            return false;
        }
    });

    Container content = getContentPane();
    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    content.add(panel);
    Factory<Device> vertexFactory = DeviceFactory.getInstance();
    Factory<ComLink> edgeFactory = ComLinkFactory.getInstance();

    final EditingModalGraphMouse<Device, ComLink> graphMouse = new EditingModalGraphMouse<>(
            vv.getRenderContext(), vertexFactory, edgeFactory);

    // Trying out our new popup menu mouse plugin...
    PopupVertexEdgeMenuMousePlugin myPlugin = new PopupVertexEdgeMenuMousePlugin();
    // Add some popup menus for the edges and vertices to our mouse plugin.
    JPopupMenu edgeMenu = new MyMouseMenus.EdgeMenu(frame);
    JPopupMenu vertexMenu = new MyMouseMenus.VertexMenu(frame);
    myPlugin.setEdgePopup(edgeMenu);
    myPlugin.setVertexPopup(vertexMenu);
    graphMouse.remove(graphMouse.getPopupEditingPlugin()); // Removes the existing popup editing plugin

    graphMouse.add(myPlugin); // Add our new plugin to the mouse  
    // AnnotatingGraphMousePlugin<Device,ComLink> annotatingPlugin =
    //   new AnnotatingGraphMousePlugin<>(vv.getRenderContext());
    //graphMouse.add(annotatingPlugin);
    // the EditingGraphMouse will pass mouse event coordinates to the
    // vertexLocations function to set the locations of the vertices as
    // they are created
    //        graphMouse.setVertexLocations(vertexLocations);
    vv.setGraphMouse(graphMouse);
    vv.addKeyListener(graphMouse.getModeKeyListener());

    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);

    //final ImageAtEdgePainter<String, String> imageAtEdgePainter = 
    //  new ImageAtEdgePainter<String, String>(vv, edge, image);
    final ScalingControl scaler = new CrossoverScalingControl();
    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton help = new JButton("Help");
    help.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(vv, instructions);
        }
    });
    JButton deploy = new JButton("Deploy");
    deploy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // OPMapping algo here
            if (simu == null) {
                return;
            }
            GraphUtil<Device, ComLink> util = new GraphUtil<>();
            for (EventProducer p : simu.getProducers()) {
                if (!p.isMapped()) {
                    JOptionPane.showMessageDialog(frame,
                            "Cannot map operators. Please deploy the producer: " + p.getName());
                    return;
                }
            }
            for (EventConsumer c : simu.getConsumers()) {
                if (!c.isMapped()) {
                    JOptionPane.showMessageDialog(frame,
                            "Cannot map operators. Please deploy the consumer: " + c.getName());
                    return;
                }
                System.out.println("-- Operator placement algorithm Greedy: " + c.getName() + " --");
                Solution init = util.initialMapping(c.getGraph());
                System.out.println(c.getGraph() + "\nInitial Mapping: " + init);
                OperatorMapping mapper = new OperatorMapping();
                long T1, T2;
                System.out.println("--- OpMapping Algo Greedy --- ");
                T1 = System.currentTimeMillis();
                Solution solution = mapper.opMapping(c.getGraph(), Topology.getInstance().getGraph(), init);
                T2 = System.currentTimeMillis();
                System.out.println(solution);
                System.out.println("Solution founded in: " + (T2 - T1) + " ms");
            }
            //                Solution init = util.initialMapping(EPGraph.getInstance().getGraph());
            //                System.out.println("Initial Mapping: " + init);
            //                OperatorMapping mapper = new OperatorMapping();
            //                long T1, T2;
            //                System.out.println("--- OpMapping Algo Greedy --- ");
            //                T1 = System.currentTimeMillis();
            //                Solution solution = mapper.opMapping(EPGraph.getInstance().getGraph(),
            //                        Topology.getInstance().getGraph(), init);
            //                T2 = System.currentTimeMillis();
            //                System.out.println(solution);
            //                System.out.println("Solution founded in: " + (T2 - T1) + " ms");
            vv.repaint();
        }
    });
    JButton run = new JButton("Run");
    run.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // run the simulation here
            System.out.println("Setting the simulation...");
            for (EventConsumer c : simu.getConsumers()) {

                for (EPUnit op : c.getGraph().getVertices()) {
                    if (op.isMapped()) {
                        op.openIOchannels();
                    } else {
                        JOptionPane.showMessageDialog(frame, "Cannot run, undeployed operators founded.");
                        return;
                    }
                }
            }
            //ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            System.out.println("Running the simulation...");
            //scheduledExecutorService.execute(runner);
            for (Device device : Topology.getInstance().getGraph().getVertices()) {
                if (!device.isAlive()) {
                    device.start();
                }
            }
            for (ComLink link : Topology.getInstance().getGraph().getEdges()) {
                if (!link.isAlive()) {
                    link.start();
                }
            }
            for (EventConsumer c : simu.getConsumers()) {
                for (EPUnit op : c.getGraph().getVertices()) {
                    if (op.isMapped() && op.getDevice() != null && !op.isAlive()) {
                        op.start();
                    }
                }
            }

        }
    });
    AnnotationControls<Device, ComLink> annotationControls = new AnnotationControls<Device, ComLink>(
            graphMouse.getAnnotatingPlugin());
    JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 0);
    slider.setMinorTickSpacing(5);
    slider.setMajorTickSpacing(30);
    slider.setPaintTicks(true);
    slider.setPaintLabels(true);
    slider.setLabelTable(slider.createStandardLabels(15));
    slider.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            JSlider slider = (JSlider) e.getSource();
            if (!slider.getValueIsAdjusting()) {
                speedSimulation(slider.getValue());
            }
        }
    });
    JPanel controls = new JPanel();
    controls.add(plus);
    controls.add(minus);
    JComboBox modeBox = graphMouse.getModeComboBox();
    controls.add(modeBox);
    controls.add(annotationControls.getAnnotationsToolBar());
    controls.add(slider);
    controls.add(deploy);
    controls.add(run);
    controls.add(help);
    content.add(controls, BorderLayout.SOUTH);
    /* Custom JPanels can be added here  */
    //
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //final GraphEditor demo = new GraphEditor();

}

From source file:com.openbravo.pos.util.ThumbNailBuilder.java

private Image createThumbNail(Image img) {
    //            MaskFilter filter = new MaskFilter(Color.WHITE);
    //            ImageProducer prod = new FilteredImageSource(img.getSource(), filter);
    //            img = Toolkit.getDefaultToolkit().createImage(prod);

    int targetw;//from  www  .  j  ava2s  .  co  m
    int targeth;

    double scalex = (double) m_width / (double) img.getWidth(null);
    double scaley = (double) m_height / (double) img.getHeight(null);
    if (scalex < scaley) {
        targetw = m_width;
        targeth = (int) (img.getHeight(null) * scalex);
    } else {
        targetw = (int) (img.getWidth(null) * scaley);
        targeth = (int) m_height;
    }

    int midw = img.getWidth(null);
    int midh = img.getHeight(null);
    BufferedImage midimg = null;
    Graphics2D g2d = null;

    Image previmg = img;
    int prevw = img.getWidth(null);
    int prevh = img.getHeight(null);

    do {
        if (midw > targetw) {
            midw /= 2;
            if (midw < targetw) {
                midw = targetw;
            }
        } else {
            midw = targetw;
        }
        if (midh > targeth) {
            midh /= 2;
            if (midh < targeth) {
                midh = targeth;
            }
        } else {
            midh = targeth;
        }
        if (midimg == null) {
            midimg = new BufferedImage(midw, midh, BufferedImage.TYPE_INT_ARGB);
            g2d = midimg.createGraphics();
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        }
        g2d.drawImage(previmg, 0, 0, midw, midh, 0, 0, prevw, prevh, null);
        prevw = midw;
        prevh = midh;
        previmg = midimg;
    } while (midw != targetw || midh != targeth);

    g2d.dispose();

    if (m_width != midimg.getWidth() || m_height != midimg.getHeight()) {
        midimg = new BufferedImage(m_width, m_height, BufferedImage.TYPE_INT_ARGB);
        int x = (m_width > targetw) ? (m_width - targetw) / 2 : 0;
        int y = (m_height > targeth) ? (m_height - targeth) / 2 : 0;
        g2d = midimg.createGraphics();
        g2d.drawImage(previmg, x, y, x + targetw, y + targeth, 0, 0, targetw, targeth, null);
        g2d.dispose();
        previmg = midimg;
    }
    return previmg;
}