I am trying to merge two images a PNG/TIFF file over a JPEG image. I am using the following code
try {
image = ImageIO.read(new File("C:\\Users\\user\\Desktop\\test\\a.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedImage overlay = null;
try {
overlay = ImageIO.read(new File("C:\\Users\\user\\Desktop\\test\\b.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// create the new image, canvas size is the max. of both image sizes
int w = Math.max(image.getWidth(), overlay.getWidth());
int h = Math.max(image.getHeight(), overlay.getHeight());
BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
// paint both images, preserving the alpha channels
Graphics2D g = combined.createGraphics();
/**Set Antialias Rendering**/
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
/**
* Draw background image at location (0,0)
* You can change the (x,y) value as required
*/
g.drawImage(image, 0, 0, null);
/**
* Draw foreground image at location (0,0)
* Change (x,y) value as required.
*/
g.drawImage(overlay, 0, 0, null);
g.dispose();
// Save as new image
try {
ImageIO.write(combined, "JPG", new File("C:\\Users\\user\\Desktop\\test\\c.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But, then final image that is forming is not according to what i want. Please refer to the attached images for clarity.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
class CombineImages {
public static void main(String[] args) throws Exception {
URL urlImage1 = new URL("http://i.stack.imgur.com/T5uTa.png");
// Load the FG image (must have transparent parts)
final Image fgImage = ImageIO.read(urlImage1);
int w = fgImage.getWidth(null);
int h = fgImage.getHeight(null);
// Create a non-trasparent BG image
final BufferedImage bgImage =
new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
// Create the final image
final BufferedImage finalImage =
new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g = finalImage.createGraphics();
g.drawImage(bgImage, 0, 0, null);
g.drawImage(fgImage, 0, 0, null);
g.dispose();
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new GridLayout(1,0,5,5));
gui.add(new JLabel(new ImageIcon(bgImage)));
gui.add(new JLabel(new ImageIcon(fgImage)));
gui.add(new JLabel(new ImageIcon(finalImage)));
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Related
I need to rotate ImageIcon to buffered image in Java. I've tried every possible way, is there any way, I already tried to convert ImageIcon to bufferedImage.
I tried every possible StackOverflow solution
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
public class Test {
public static void main(String[] args) {
// Create GUI
GUI gui = new GUI();
// Schedule task; rotate img every 1s
Timer timer = new Timer(1000, e -> gui.rotateImg());
timer.setRepeats(true);
timer.start();
}
static class GUI extends JFrame {
// Web url for image of cute doggo
private static final String IMAGE_URL = "https://i.pinimg.com/736x/10/b2/6b/10b26b498bc3fcf55c752c4e6d9bfff7.jpg";
// Cache image and UI components for rotation
private BufferedImage image;
private ImageIcon icon;
private JLabel label;
// Create new JFrame
public GUI() {
// Config grame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700, 700);
setLocationRelativeTo(null);
URL url;
image = null;
try {
// Download + cache image from web
url = new URL(IMAGE_URL);
image = ImageIO.read(url);
} catch (IOException e) {
// Handle error downloading
System.out.println("Failed to read image due to: " + e.getMessage());
} finally {
// On success - create/cache UI components
if (image != null) {
// In this example I am using a label here to display an ImageIcon
// But at root the ImageIcon is holding a BufferedImage which is what we're modifying on rotation
add(label = new JLabel(icon = new ImageIcon(image)));
}
}
// Show configured JFrame
setVisible(true);
}
public void rotateImg() {
if (image == null) return;
// Rotate image
BufferedImage rotated = rotateImg(image, Math.toRadians(90));
// Add rotated image
icon.setImage(image = rotated);
// Repaint
label.revalidate();
label.repaint();
}
// SRC: https://www.delftstack.com/howto/java/java-rotate-image/
private BufferedImage rotateImg(BufferedImage img, double degrees) {
int w = img.getWidth(), h = img.getHeight();
BufferedImage imgCopy = new BufferedImage(w, h, img.getType());
Graphics2D g2d = imgCopy.createGraphics();
g2d.rotate(degrees, w / 2, h / 2);
g2d.drawImage(img, null, 0, 0);
return imgCopy;
}
}
}
File sourceImageFile = new File("C:\Users\Documents\NetBeansProjects\MyProject\src\asian\paints\images\stations.png");
BufferedImage sourceImage = ImageIO.read(sourceImageFile);
File watermarkImageFile = new File("C:\\Users\\Documents\\NetBeansProjects\\MyProject\\src\\asian\\paints\\images\\error_indicate.png");
BufferedImage watermarkImage = ImageIO.read(watermarkImageFile);
File destImageFile = new File("C:\\Users\\Desktop\\watermarked.png");
// initializes necessary graphic properties
Graphics2D g2d = (Graphics2D) sourceImage.getGraphics();
AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
g2d.setComposite(alphaChannel);
new Timer(0, new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
try {
Jedis jedis = new Jedis("localhost");
// calculates the coordinate where the image is painted
int topLeftX = Integer.parseInt(jedis.get("x")) ;
int topLeftY = Integer.parseInt(jedis.get("y")) ;
System.out.println("x " + topLeftX);
System.out.println("y " + topLeftY);
// paints the image watermark
g2d.drawImage(watermarkImage, topLeftX, topLeftY, null);
ImageIO.write(sourceImage, "png", destImageFile);
g2d.dispose();
// System.out.println("The image watermark is added to the image.");
ImageIcon iconLogo = new ImageIcon("C:\\Users\\Desktop\\watermarked.png");
// In init() method write this code
jLabel1.setIcon(iconLogo);
} catch (IOException ex) {
System.err.println(ex);
}
}
}).start();
The above program changes the watermark position only for the first time when the executed. It will not change its position after that.
When I try to rotate an image it appears that a part of the background turns black (my images are transparents)
Background white
Part of background turns black
Here's the code that rotate the image :
public BufferedImage rotate(int height, int width, BufferedImage originalImg, int angle) {
BufferedImage rotateImage = null;
try {
rotateImage = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB);
AffineTransform a90 = AffineTransform.getRotateInstance(Math.toRadians(angle), height / 2, width / 2);
AffineTransformOp op90 = new AffineTransformOp(a90, AffineTransformOp.TYPE_BILINEAR);
op90.filter(originalImg, rotateImage);
}
catch (Exception e) {
System.err.println(e);
}
return rotateImage;
}
So, I downloaded you "original" image (which is not square), modified it so it was square, run your code, got a java.awt.image.ImagingOpException: Unable to transform src image exception, changed BufferedImage.TYPE_INT_RGB to BufferedImage.TYPE_INT_ARGB and got...
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
try {
BufferedImage img = ImageIO.read(Main.class.getResource("/Block.jpg"));
BufferedImage rotate = rotate(img.getHeight(), img.getWidth(), img, 90);
JPanel panel = new JPanel();
panel.add(new JLabel(new ImageIcon(img)));
panel.add(new JLabel(new ImageIcon(rotate)));
JOptionPane.showMessageDialog(null, panel);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static BufferedImage rotate(int height, int width, BufferedImage originalImg, int angle) {
BufferedImage rotateImage = null;
try {
rotateImage = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
AffineTransform a90 = AffineTransform.getRotateInstance(Math.toRadians(angle), height / 2, width / 2);
AffineTransformOp op90 = new AffineTransformOp(a90, AffineTransformOp.TYPE_BILINEAR);
op90.filter(originalImg, rotateImage);
} catch (Exception e) {
e.printStackTrace();
}
return rotateImage;
}
}
My, "gut" feeling is to also modify the rotate method, as it shouldn't need width and height values;
public static BufferedImage rotate(BufferedImage originalImg, int angle) {
BufferedImage rotateImage = null;
try {
rotateImage = new BufferedImage(originalImg.getWidth(), originalImg.getHeight(), BufferedImage.TYPE_INT_ARGB);
AffineTransform a90 = AffineTransform.getRotateInstance(Math.toRadians(angle), originalImg.getWidth() / 2, originalImg.getHeight() / 2);
AffineTransformOp op90 = new AffineTransformOp(a90, AffineTransformOp.TYPE_BILINEAR);
op90.filter(originalImg, rotateImage);
} catch (Exception e) {
e.printStackTrace();
}
return rotateImage;
}
it should be using the original image's dimensions directly. This is will highlight possible errors in your images. This also assumes that you only want to rotate the image by increments of 90 degrees
Hey,I'm trying to make a program which loads a colored image as grayscale on canvas and then returns the color to the pixels clicked.
I'm stuck here when the setrgb() method is not doing what its supposed to. I have copied the color from original image by getRGB() and am using setRGB() to assign it to a new image.
I have tried to output both the pixel color values but they are not same.
Please help me out with this.
Here's the code so far:
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.awt.*;
import java.applet.*;
#SuppressWarnings("serial")
public class BlackWHite extends Applet implements MouseListener
{
String str;
int x=0,y=0;
BufferedImage bimg = null;
BufferedImage nimg = null;
BufferedImage image=null;
double image_width =300;
double image_height=300;
private Image img;
public void init()
{
img = null;
str = JOptionPane.showInputDialog(null, "Enter file location : ",
"Choose Image", 1);
BufferedImage image=null;
try {
image = ImageIO.read(new File(str));
} catch (IOException e) {
e.printStackTrace();
}
//getting width and height of image
image_width = image.getWidth();
image_height = image.getHeight();
BufferedImage img = image;
//drawing a new image
bimg = new BufferedImage((int)image_width, (int)image_height,
BufferedImage.TYPE_BYTE_GRAY);
Graphics2D gg = bimg.createGraphics();
gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
nimg = new BufferedImage((int)image_width, (int)image_height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = nimg.createGraphics();
g.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
addMouseListener(this);
}
public void loadImage()
{
try {
img = getImage(getCodeBase(), "blackwhiteimage.jpg");
} catch(Exception e) {
}
}
public void paint(Graphics g)
{
try {
image = ImageIO.read(new File(str));
} catch (IOException e) {
e.printStackTrace();
}
convert(); //converting the image
if (img == null)
loadImage(); //draw
g.drawImage(img, 0, 0, this);
int c = image.getRGB(x,y);
int red = (c & 0x0000FFFF) >> 16;
int green = (c & 0x0000FFFF) >> 8;
int blue = c & 0x0000FFFF;
c=(red << 16) | (green << 8) | blue;
System.out.print("c="+c);
nimg=bimg;
nimg.setRGB(x,y,c);
try {
ImageIO.write(nimg, "jpg", new File("pixelcolor.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(nimg, 0, 0, this);
int f = nimg.getRGB(x,y);
System.out.println("f="+f);
}
void convert() {
try {
//saving black and white image onto drive
ImageIO.write(bimg, "jpg", new File("blackwhiteimage.jpg"));
} catch (Exception e) {
System.out.println(e);
}
}
#Override
public void mouseClicked(MouseEvent me) {
x = me.getX();
y = me.getY();
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
The fundamental problem is that you are trying to set the colour of the image in gray scale colour space. That is not the only bug in the applet, but you can start with it. Try using another way to convert the image to gray scale while keeping it in RGBA, such as those shown here: convert a RGB image to grayscale Image reducing the memory in java
I'm trying to capture the screen and then paint the image to a JFrame recursively while scaling the image (to create that effect you get when you look at a mirror in a mirror).
I'm having trouble with my code - it doesn't paint any graphics. What am I doing wrong?
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class ScreenCapture extends JFrame {
BufferedImage screenCapture;
Graphics screenCaptureGraphics;
private static int recurseCount = 0;
private static float $scale = 0.9f;
private static float scale = 1.0f;
private static int height;
private static int width;
ScreenCapture() {
try {
screenCapture = new Robot().createScreenCapture(
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );
height = screenCapture.getHeight();
width = screenCapture.getWidth();
setSize(new Dimension(width, height));
addWindowListener(new LocalWindowListener());
Graphics g = recursiveDraw(screenCapture, getGraphics());
paint(g);
} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Graphics recursiveDraw(BufferedImage img, Graphics imgG) {
updateScale(++recurseCount);
float newWidth = scale*width;
float newHeight = scale*height;
int w = (int) newWidth;
int h = (int) newHeight;
System.out.println("W: " + w + "; H: " + h);
if (w >= 10 && h >= 10) {
//scale image
System.out.print("Creating scaled Image...");
Image scaled = img.getScaledInstance(w, h, Image.SCALE_SMOOTH);
BufferedImage resized = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
imgG = resized.createGraphics();
imgG.drawImage(scaled, 0, 0, null);
System.out.println("...Image drawn to graphics");
//return new graphics
return recursiveDraw(resized, imgG);
} else {
//otherwise return old graphics
System.out.println("Completed.");
return imgG;
}
}
private void updateScale(int count) {
for (int i=0; i<count; i++) {
scale *= $scale;
}
System.out.println("Updated scale: " + scale + "; Recurse count: " + recurseCount);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ScreenCapture().setVisible(true);
}
});
}
private class LocalWindowListener extends WindowAdapter {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0); return;
}
}
}
EDIT:
This is what I tried after #andrew-thompson 's answer:
ScreenCapture() {
try {
screenCapture = new Robot().createScreenCapture(
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );
height = screenCapture.getHeight();
width = screenCapture.getWidth();
setSize(new Dimension(width, height));
addWindowListener(new LocalWindowListener());
setLayout(new GridLayout());
add(new PaintPanel());
} catch (HeadlessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class PaintPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
g=recursiveDraw(screenCapture, g);
//what to do with g?
}
}
I still have the same problem where I don't know how to make the BufferedImage paint to the graphics.
would separate out your Swing code from your recursive image creation code. In fact consider creating a static method that creates and returns the BufferedImage and that has no Swing code in it. Then have your GUI call the method when it wishes, and take the image and either write it to disk or display it in a JLabel's ImageIcon.
When I did this (today in fact), I created a recursive method with this signature
private static void recursiveDraw(BufferedImage img, Graphics imgG, double scale) {
and with this method body (in pseudo-code)
start recursiveDraw method
// most important: all recursions must have a good ending condition:
get img height and width. If either <= a min, return
create a BufferedImage, smlImg, for the smaller image using the height,
width and scale factor
Get the Graphics object, smlG, from the small image
Use smlG.drawImage(...) overload to draw the big image in shrunken
form onto the little image
recursively call recursiveDraw passing in smlImg, smlG, and scale.
dispose of smlG
draw smlImg (the small image) onto the bigger one using the bigger's
Graphics object (passed into this method) and a different
overload of the drawImage method.
end recursiveDraw method
This algorithm resulted in images like:
For example:
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class RecursiveDrawTest {
private static final Color BACKGRND_1 = Color.green;
private static final Color BACKGRND_2 = Color.MAGENTA;
private static final Color FOREGRND_1 = Color.blue;
private static final Color FOREGRND_2 = Color.RED;
private static void createAndShowGui() {
final JPanel mainPanel = new JPanel(new BorderLayout());
final JSlider slider = new JSlider(50, 90, 65);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
JPanel southPanel = new JPanel();
southPanel.add(new JLabel("Percent Size Reduction:"));
southPanel.add(slider);
southPanel.add(new JButton(new AbstractAction("Create Recursive Image") {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
double scale = slider.getValue() / 100.0;
BufferedImage img = createRecursiveImg(scale);
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon);
Window win = SwingUtilities.getWindowAncestor(mainPanel);
JDialog dialog = new JDialog(win, "Image", ModalityType.MODELESS);
dialog.getContentPane().add(label);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
} catch (AWTException e) {
e.printStackTrace();
}
}
}));
mainPanel.add(new JScrollPane(new JLabel(new ImageIcon(createLabelImg()))),
BorderLayout.CENTER);
mainPanel.add(southPanel, BorderLayout.PAGE_END);
JFrame frame = new JFrame("RecursiveDrawTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// create a background image to display in a JLabel so that the GUI
// won't be boring.
private static BufferedImage createLabelImg() {
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int width = (5 * d.width) / 6;
int height = (5 * d.height) / 6;
BufferedImage img = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(new GradientPaint(0, 0, BACKGRND_1, 40, 40, BACKGRND_2, true));
g2.fillRect(0, 0, width, height);
g2.setPaint(new GradientPaint(0, height, FOREGRND_1, 40, height - 40, FOREGRND_2, true));
g2.fillOval(0, 0, 2 * width, 2 * height);
g2.dispose();
return img;
}
// non-recursive image to get the initial image that will be drawn recursively
public static BufferedImage createRecursiveImg(double scale) throws AWTException {
Robot robot = new Robot();
Dimension screenSz = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRect = new Rectangle(screenSz);
BufferedImage img = robot.createScreenCapture(screenRect);
Graphics g = img.getGraphics();
recursiveDraw(img, g, scale); // call recursive method
g.dispose();
return img;
}
// recursive method to draw image inside of image
private static void recursiveDraw(BufferedImage img, Graphics g, double scale) {
int w = img.getWidth();
int h = img.getHeight();
int smlW = (int)(w * scale);
int smlH = (int)(h * scale);
// criteria to end recursion
if (smlW <= 1 || smlH <= 1) {
return;
}
BufferedImage smlImg = new BufferedImage(smlW, smlH, BufferedImage.TYPE_INT_ARGB);
Graphics smlG = smlImg.getGraphics();
// draw big image in little image, scaled to little image
smlG.drawImage(img, 0, 0, smlW, smlH, null);
// recursive call
recursiveDraw(smlImg, smlG, scale);
smlG.dispose(); // clear resources when done with them
// these guys center the smaller img on the bigger
int smlX = (w - smlW) / 2;
int smlY = (h - smlH) / 2;
// draw small img on big img
g.drawImage(smlImg, smlX, smlY, smlW, smlH, null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Graphics g = recursiveDraw(screenCapture, getGraphics());
Don't call getGraphics(). Override paint(Graphics)1 & use the supplied Graphics instance.
When using Swing, it is actually best to override the paintComponent(Graphics) method of a JComponent or JPanel. Then add that to the top-level container.
Is this what you are hoping for :
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*;
public class CaptureScreen extends JPanel
{
private BufferedImage screenShot;
private JLabel imageLabel;
private BufferedImage secondScreenShot;
public void createAndDisplayGUI()
{
JFrame frame = new JFrame("CAPTURE SCREEN");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
//imageLabel = new JLabel();
//getImageForLabel();
//add(imageLabel);
frame.getContentPane().add(this);
frame.setSize(600, 600);
frame.setVisible(true);
}
private void getImageForLabel()
{
Robot robot = null;
try
{
robot = new Robot();
}
catch(Exception e)
{
e.printStackTrace();
}
screenShot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIcon icon = new ImageIcon(screenShot);
imageLabel.setIcon(icon);
}
public void paintComponent(Graphics g)
{
Robot robot = null;
try
{
robot = new Robot();
}
catch(Exception e)
{
e.printStackTrace();
}
screenShot = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
secondScreenShot = getScaledImage((Image) screenShot, 300, 300);
g.drawImage(screenShot, 0, 0, null);
g.drawImage(secondScreenShot, 150, 150, null);
}
private BufferedImage getScaledImage(Image srcImg, int w, int h)
{
BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
Graphics2D g2 = resizedImg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(srcImg, 0, 0, w, h, null);
g2.dispose();
return resizedImg;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CaptureScreen().createAndDisplayGUI();
}
});
}
}
Here is the output :
Get rid of the recursion. Create a single buffered image of the correct size and create a Graphics object for it. Just use a loop to draw progressively smaller scaled images down to whatever threshold you choose. Finally use g.drawImage() inside paintComponent() to draw your image to the screen. If you keep the recursion you need to pass the image and continually overlay the scaled down image. You do not need to return anything from the method.