Java 2D rotate BufferedImage - java

This question was answered many time but I still can't apply it to my situation.
I want to rotate image on 90 degrees clockwise.
I'm currently having following code:
private void writeImage(BufferedImage sourceImage, String Path) throws IOException {
BufferedImage result;
Graphics2D g;
AffineTransform at = new AffineTransform();
//Do some magic right here to correctly rotate the image itself
if (sourceImage.getWidth() > sourceImage.getHeight()) {
//Do some stuff that somehow works:
result = new BufferedImage(sourceImage.getHeight(null), sourceImage.getWidth(null), BufferedImage.TYPE_INT_RGB);
g = result.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// Anti-alias!
g.translate((result.getHeight() - result.getWidth()) / 2, (result.getHeight() - result.getWidth()) / 2);
g.rotate(Math.toRadians(90f), sourceImage.getHeight() / 2, sourceImage.getWidth() / 2);//simple try
} else {
result = new BufferedImage(sourceImage.getWidth(null), sourceImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
g = result.createGraphics();
}
//result = new BufferedImage(sourceImage.getWidth(null), sourceImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
//g = result.createGraphics();
/*
if (result.getWidth() > result.getHeight()) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// Anti-alias!
//g.translate(170, 0);
g.rotate(Math.toRadians(90));
//g.translate((result.getHeight() - result.getWidth()) / 4, (result.getHeight() - result.getWidth()) / 4);
//g.rotate(Math.PI / 2, result.getHeight() / 2, result.getWidth() / 2);
//g.drawImage(sourceImage, 0, 0, result.getHeight(), result.getWidth(), Color.WHITE, null);
//AffineTransformOp op = new AffineTransformOp(rotateClockwise90(result), AffineTransformOp.TYPE_BILINEAR);
//op.filter(sourceImage, result);
int tempHeight = result.getHeight();
int tempWidth = result.getWidth();
BufferedImage rotated = resize(result, tempHeight, tempWidth);
//result = rotated;
result = resize(result, result.getHeight(), result.getWidth());
}*/
g.drawImage(sourceImage, 0, 0, result.getWidth(), result.getHeight(), Color.WHITE, null);
//g.drawImage(sourceImage, at, null);
g.dispose();
//BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
//g = bufferedImage.createGraphics();
//Color.WHITE estes the background to white. You can use any other color
//g.drawImage(image, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), Color.WHITE, null);
File output = new File(Path);
OutputStream out = new FileOutputStream(output);
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(out);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
if (param.canWriteCompressed()) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(IMAGE_QUALITY);
}
writer.write(null, new IIOImage(result, null, null), param);
out.close();
ios.close();
writer.dispose();
}
Current Result
The source image and 'BufferedImage sourceImage' looks like this:
Source Image
And what I expect to see is this:
Expected
Thanks!

Here is a more general solution that will allow rotation of any specified degrees:
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class Rotation
{
public static BufferedImage rotateImage(BufferedImage original, double theta)
{
// Determine the size of the rotated image
double cos = Math.abs(Math.cos(theta));
double sin = Math.abs(Math.sin(theta));
double width = original.getWidth();
double height = original.getHeight();
int w = (int)(width * cos + height * sin);
int h = (int)(width * sin + height * cos);
// Create empty image and fill in background
BufferedImage rotated = new BufferedImage(w, h, original.getType());
Graphics2D g2 = rotated.createGraphics();
g2.setPaint(UIManager.getColor("Panel.background"));
g2.fillRect(0, 0, w, h);
// Rotate the image
double x = w/2;
double y = h/2;
AffineTransform at = AffineTransform.getRotateInstance(theta, x, y);
x = (w - width)/2;
y = (h - height)/2;
at.translate(x, y);
g2.drawRenderedImage(original, at);
g2.dispose();
return rotated;
}
private static void createAndShowGUI()
{
BufferedImage bi;
try
{
String path = "mong.jpg";
ClassLoader cl = Rotation.class.getClassLoader();
bi = ImageIO.read( cl.getResourceAsStream(path) );
}
catch (Exception e) { return; }
JLabel label = new JLabel( new ImageIcon( bi ) );
label.setBorder( new LineBorder(Color.RED) );
label.setHorizontalAlignment(JLabel.CENTER);
JPanel wrapper = new JPanel();
wrapper.add( label );
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
slider.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
int value = slider.getValue();
BufferedImage rotated = Rotation.rotateImage(bi, Math.toRadians(value) );
label.setIcon( new ImageIcon(rotated) );
}
});
JFrame frame = new JFrame("Rotation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(wrapper, BorderLayout.CENTER);
frame.add(slider, BorderLayout.PAGE_END);
frame.setSize(600, 600);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}

Try
g.drawImage(sourceImage, 0, 0, sourceImage.getWidth(), sourceImage.getHeight(), Color.WHITE, null);

Related

Java Printing on thermal printer cutts off content from either side

I am trying to print content from a bean object to a thermal printer with the code above, it works perfectly on other printers but not on a thermal printer,
Content is cutt-off from either side and only incomplete content placed in the middle of the paper roll is visible.
I am using barbacue to generate a bar-code and draw the image to the graphic as well,
Any help would be highly appreciated.
package com.iwar.utility;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
import net.sourceforge.barbecue.Barcode;
import net.sourceforge.barbecue.BarcodeException;
import net.sourceforge.barbecue.BarcodeFactory;
import net.sourceforge.barbecue.BarcodeImageHandler;
import net.sourceforge.barbecue.output.OutputException;
import com.iware.connection.db.GetStuff;
import com.iware.pos.beans.PrintableBean;
public class PrinterManager {
public static boolean PrintTicket(final PrintableBean printable, final String input){
try
{
// printable is a bean containing all the information to be printed.
final Book book = new Book();//java.awt.print.Book
// here i create a new printable object where draw all the content from the bean //object onto the graphic g
Printable b= new Printable() {
#Override
public int print(Graphics g, PageFormat pf, int page)
throws PrinterException {
// TODO Auto-generated method stub
// We have only one page, and 'page'
// is zero-based
if (page > 0) {
return NO_SUCH_PAGE;
}
// User (0,0) is typically outside the
// imageable area, so we must translate
// by the X and Y values in the PageFormat
// to avoid clipping.
// Paper paper = pf.getPaper();
Paper paper = new Paper();
double paperWidth = 3;//3.25
double paperHeight = 5;//11.69
double leftMargin = 0.12;
double rightMargin = 0.10;
double topMargin = 0.75;
double bottomMargin = 0.01;
paper.setSize(paperWidth * 100, paperHeight * 100);
paper.setImageableArea(leftMargin * 200, topMargin * 200,
(paperWidth - leftMargin - rightMargin) * 200,
(paperHeight - topMargin - bottomMargin) * 200);
pf.setOrientation(PageFormat.PORTRAIT);
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
g.setFont(new Font("Copperplate Gothic Bold", Font.CENTER_BASELINE, 10));
g.drawString("HUB ENTERTAINMENT LIMITED", 0, 25);
g.setFont(new Font("Copperplate Gothic Bold", Font.CENTER_BASELINE, 8));
g.setColor(Color.BLACK);
g.drawString("Ticket Number : " + printable.getTicket_entry_number(), 0, 90);
g.drawString("Ticket Type : " + printable.getTicket_type(), 0, 110);
g.drawString("Movie Name : " + printable.getMovie_name(), 0, 130);
g.drawString("Date : " + printable.getShow_date(), 0, 150);
g.drawString("Time : " + printable.getSpecific_time(), 0, 170);
g.drawString("Theater : " + printable.getTheater(), 0, 190);
g.drawString("Cinema Room : " + printable.getCinema_room(), 0, 210);
g.drawString("Cost : " + printable.getCost(), 0, 230);
g.drawString("Cashier : " + printable.getCashier(), 0, 250);
g.drawString("Printed On : " + GetStuff.getCurrentDate(), 0, 270);
g.drawString("Seat Number : " + input , 0, 290);
g.drawLine(380, 310, 0, 310);
g.drawString("Ticket Number : " + printable.getTicket_entry_number(), 0, 350);
g.drawString("Ticket Type : " + printable.getTicket_type(), 0, 370);
g.drawString("Movie Name : " + printable.getMovie_name(), 0, 390);
g.drawString("Date : " + printable.getShow_date(), 0, 410);
g.drawString("Time : " + printable.getSpecific_time(), 0, 430);
g.drawString("Theater : " + printable.getTheater(), 0, 450);
g.drawString("Cinema Room : " + printable.getCinema_room(), 0, 470);
g.drawString("Cost : " + printable.getCost(), 0, 490);
g.drawString("Cashier : " + printable.getCashier(), 0, 510);
g.drawString("Printed On : " + GetStuff.getCurrentDate(), 0, 530);
g.drawString("Seat Number : " + input, 0, 550);
g.drawLine(380, 570, 0, 570);
// String combo = "Combo";
BufferedImage img = null;
g.setFont(new Font("Eras Bold ITC", Font.ROMAN_BASELINE, 20));
if(printable.getTicket_type().equals("VIP")){
g.drawString("VIP SEATING", 0, 610);
g.drawString("DRINK + SNACK", 0, 630);
try {
String number = Integer.toString(printable.getTicket_entry_number());
Barcode barCode = BarcodeFactory.createCode128(number);
img = BarcodeImageHandler.getImage(barCode);
//ImageIO.read(new File("image/logo.png"));
} catch (BarcodeException | OutputException e) {
JOptionPane.showMessageDialog(null,"Failed to Load Image");
}
int w = img.getWidth(null);
int h = img.getHeight(null);
BufferedImage bi = new
BufferedImage(w, h, BufferedImage.TRANSLUCENT);
g = bi.getGraphics();
g.drawImage(img, 0, 0, null);
/* Draw the image, applying the filter */
g2d.drawImage(bi, null, 0, 650);
}else if(printable.getTicket_type().equals("Combo")){
g.drawString("FREE SODA", 0, 610);
g.drawString("FREE PORPCORN", 0, 630);
try {
String number = Integer.toString(printable.getTicket_entry_number());
Barcode barCode = BarcodeFactory.createCode128(number);
img = BarcodeImageHandler.getImage(barCode);
//ImageIO.read(new File("image/logo.png"));
} catch (BarcodeException | OutputException e) {
JOptionPane.showMessageDialog(null,"Failed to Load Image");
}
int w = img.getWidth(null);
int h = img.getHeight(null);
BufferedImage bi = new
BufferedImage(w, h, BufferedImage.TRANSLUCENT);
g = bi.getGraphics();
g.drawImage(img, 0, 0, null);
/* Draw the image, applying the filter */
g2d.drawImage(bi, null, 0, 650);
}else{
try {
String number = Integer.toString(printable.getTicket_entry_number());
Barcode barCode = BarcodeFactory.createCode128(number);
img = BarcodeImageHandler.getImage(barCode);
//ImageIO.read(new File("image/logo.png"));
} catch (BarcodeException | OutputException e) {
JOptionPane.showMessageDialog(null,"Failed to Load Image");
}
int w = img.getWidth(null);
int h = img.getHeight(null);
BufferedImage bi = new
BufferedImage(w, h, BufferedImage.TRANSLUCENT);
g = bi.getGraphics();
g.drawImage(img, 0, 0, null);
/* Draw the image, applying the filter */
g2d.drawImage(bi, null, 0, 590);
}
BufferedImage img2 = null;
try {
img2 = ImageIO.read(new File("images/logo.png"));
} catch (IOException e) {
}
int wi = 150; //img.getWidth(null);
int hi = 50; //img.getHeight(null);
BufferedImage bin = new
BufferedImage(wi, hi, BufferedImage.TRANSLUCENT);
g = bin.getGraphics();
g.drawImage(img2, 0, 0, null);
/* Draw the image, applying the filter */
g2d.drawImage(bin, null, 0, 26);
book.append(this, pf);
// tell the caller that this page is part
// of the printed document
return PAGE_EXISTS;
}
};
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(b);
if (job.printDialog())
{
//job.setPageable(book);
job.print();
return true;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
}

Java rotating an ImageBuffer fails

I am trying to rotate an instance of a BufferImage named pic when I try this it resizes and skews and crops the image, any advice to get it to work properly
public void rotate(double rads){
AffineTransform tx = new AffineTransform();
tx.rotate(rads,pic.getWidth()/2,pic.getHeight()/2);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
pic = op.filter(pic, null);
}
When I have it rotate 90˚ it works fine so I'm wondering if the problem is that it is the shape of the image?
For use with AffineTransform, you can square an image using something like this:
private BufferedImage getImage(String name) {
BufferedImage image;
try {
image = ImageIO.read(new File(name));
} catch (IOException ioe) {
return errorImage;
}
int w = image.getWidth();
int h = image.getHeight();
int max = Math.max(w, h);
max = (int) Math.sqrt(2 * max * max);
BufferedImage square = new BufferedImage(
max, max, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = square.createGraphics();
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawImage(image, (max - w) / 2, (max - h) / 2, null);
g2d.dispose();
return square;
}

What is BufferedImageOp stands for?

I just want to enlarge a BufferedImage and make a watermark on it.Here is my code.
BufferedImage image = GetHtmlImage(doc, base_url, width, -1);
if (image.getHeight() < MaxShortHeight) {
return "";
}
BufferedImage gimage = new BufferedImage(image.getWidth(), image.getHeight() + 20, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = gimage.createGraphics();
g2.setBackground(Color.WHITE);
g2.drawImage(image, BufferedImageOp, 0, 0);
g2.setColor(Color.BLACK);
g2.drawString("Press by Shisoft WebFusion http://www.shisoft.net/", 10, image.getHeight() - 10);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(gimage, "jpeg", os);
At 'g2.drawImage(image, BufferedImageOp, 0, 0);'.I don't know what is BufferedImageOp.Could someone make an example.
Thank you.

Creating thumbnail views of images using Java

I have an application where i need to select a folder containing pictures and need to display a thumbnail view of those images using Java . I dont have any idea as to how to represent images in a thumbnail format .
Any resources like code examples , theory or links would be really helpful.
Thank You
I have this code that I use in one of my projects. I found on the net a while ago (not sure where but if anyone recognises it please let me know so I can reference it):
private static byte[] createThumbnail(byte[] bytes)
{
try
{
double scale;
int sizeDifference, originalImageLargestDim;
Image inImage = ImageIO.read(new ByteArrayInputStream(bytes));
//find biggest dimension
if(inImage.getWidth(null) > inImage.getHeight(null))
{
scale = (double)LARGEST_DIMENSION/(double)inImage.getWidth(null);
sizeDifference = inImage.getWidth(null) - LARGEST_DIMENSION;
originalImageLargestDim = inImage.getWidth(null);
}
else
{
scale = (double)LARGEST_DIMENSION/(double)inImage.getHeight(null);
sizeDifference = inImage.getHeight(null) - LARGEST_DIMENSION;
originalImageLargestDim = inImage.getHeight(null);
}
//create an image buffer to draw to
BufferedImage outImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB); //arbitrary init so code compiles
Graphics2D g2d;
AffineTransform tx;
if(scale < 1.0d) //only scale if desired size is smaller than original
{
int numSteps = sizeDifference / 100;
int stepSize = sizeDifference / numSteps;
int stepWeight = stepSize/2;
int heavierStepSize = stepSize + stepWeight;
int lighterStepSize = stepSize - stepWeight;
int currentStepSize, centerStep;
double scaledW = inImage.getWidth(null);
double scaledH = inImage.getHeight(null);
if(numSteps % 2 == 1) //if there's an odd number of steps
centerStep = (int)Math.ceil((double)numSteps / 2d); //find the center step
else
centerStep = -1; //set it to -1 so it's ignored later
Integer intermediateSize = originalImageLargestDim, previousIntermediateSize = originalImageLargestDim;
for(Integer i=0; i<numSteps; i++)
{
if(i+1 != centerStep) //if this isn't the center step
{
if(i == numSteps-1) //if this is the last step
{
//fix the stepsize to account for decimal place errors previously
currentStepSize = previousIntermediateSize - LARGEST_DIMENSION;
}
else
{
if(numSteps - i > numSteps/2) //if we're in the first half of the reductions
currentStepSize = heavierStepSize;
else
currentStepSize = lighterStepSize;
}
}
else //center step, use natural step size
{
currentStepSize = stepSize;
}
intermediateSize = previousIntermediateSize - currentStepSize;
scale = (double)intermediateSize/(double)previousIntermediateSize;
scaledW = (int)scaledW*scale;
scaledH = (int)scaledH*scale;
outImage = new BufferedImage((int)scaledW, (int)scaledH, BufferedImage.TYPE_INT_RGB);
g2d = outImage.createGraphics();
g2d.setBackground(Color.WHITE);
g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
tx = new AffineTransform();
tx.scale(scale, scale);
g2d.drawImage(inImage, tx, null);
g2d.dispose();
inImage = new ImageIcon(outImage).getImage();
previousIntermediateSize = intermediateSize;
}
}
else
{
//just copy the original
outImage = new BufferedImage(inImage.getWidth(null), inImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
g2d = outImage.createGraphics();
g2d.setBackground(Color.WHITE);
g2d.clearRect(0, 0, outImage.getWidth(), outImage.getHeight());
tx = new AffineTransform();
tx.setToIdentity(); //use identity matrix so image is copied exactly
g2d.drawImage(inImage, tx, null);
g2d.dispose();
}
//JPEG-encode the image and write to file.
ByteArrayOutputStream os = new ByteArrayOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
encoder.encode(outImage);
return os.toByteArray();
}
catch(Exception e)
{
throw new RuntimeException(e);
}
}
The following code scales the entire image into an area. You can copy-paste the code and run it to see what it does.
The interesting call is g2d.drawImage(img, 0, 0, thumb.getWidth() - 1, thumb.getHeight() - 1, 0, 0, img.getWidth() - 1, img.getHeight() - 1, null); which copies the image into the thumbnail, scaling it to fit.
If you want different scalings to preserve the aspect ratio you could decide to use scale() on the g2d, or select a different source coordinates.
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ThumbnailFactory {
public ThumbnailFactory() {
}
public void run(String folder) {
File dir = new File(folder);
for (File file : dir.listFiles()) {
createThumbnail(file);
}
}
private void createThumbnail(File file) {
try {
// BufferedImage is the best (Toolkit images are less flexible)
BufferedImage img = ImageIO.read(file);
BufferedImage thumb = createEmptyThumbnail();
// BufferedImage has a Graphics2D
Graphics2D g2d = (Graphics2D) thumb.getGraphics();
g2d.drawImage(img, 0, 0,
thumb.getWidth() - 1,
thumb.getHeight() - 1,
0, 0,
img.getWidth() - 1,
img.getHeight() - 1,
null);
g2d.dispose();
ImageIO.write(thumb, "PNG", createOutputFile(file));
} catch (Exception e) {
e.printStackTrace();
}
}
private File createOutputFile(File inputFile) {
// You'll want something better than this...
return new File(inputFile.getAbsolutePath()
+ ".thumb.png");
}
private BufferedImage createEmptyThumbnail() {
return new BufferedImage(100, 200,
BufferedImage.TYPE_INT_RGB);
}
public static void main(String[] args) {
ThumbnailFactory fac = new ThumbnailFactory();
fac.run("c:\\images");
}
}

How to resize and rotate an image

i want to rotate an image and in next level i want to resize it plese
help me.
i create a class that extended from JPanel and override paintComponent() method
for drawing image.
public class NewJPanel extends javax.swing.JPanel {
/** Creates new form NewJPanel */
public NewJPanel() {
initComponents();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 20, 20, this);
}
Here is some code I use. You can modify it to fit your needs.
Resize Image:
/**
* Resizes the image
*
* #param filePath File path to the image to resize
* #param w Width of the image
* #param h Height of the image
* #return A resized image
*/
public ImageIcon resizeImage(String filePath, int w, int h) {
String data = filePath;
BufferedImage bsrc, bdest;
ImageIcon theIcon;
//scale the image
try {
if (dataSource == DataTypeEnum.file) {
bsrc = ImageIO.read(new File(data));
} else {
bsrc = ImageIO.read(new URL(filePath));
}
bdest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bdest.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance(
(double) w / bsrc.getWidth(), (double) h / bsrc.getHeight());
g.drawRenderedImage(bsrc, at);
//add the scaled image
theIcon = new ImageIcon(bdest);
return theIcon;
} catch (Exception e) {
Window.getLogger().warning("This image can not be resized. " +
"Please check the path and type of file.");
//restore the old background
return null;
}
}
Rotate Image:
NOTE: The angle is in radians
public static BufferedImage rotate(BufferedImage image, double angle) {
double sin = Math.abs(Math.sin(angle)),
cos = Math.abs(Math.cos(angle));
int w = image.getWidth(),
h = image.getHeight();
int neww = (int) Math.floor(w * cos + h * sin),
newh = (int) Math.floor(h * cos + w * sin);
GraphicsConfiguration gc = getDefaultConfiguration();
BufferedImage result =
gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
Graphics2D g = result.createGraphics();
g.translate((neww - w) / 2, (newh - h) / 2);
g.rotate(angle, w / 2, h / 2);
g.drawRenderedImage(image, null);
g.dispose();
return result;
}
Without giving away a full solution
Graphics2D has rotate and scale functions.
Use the BufferedImage class
BufferedImage newImg = new BufferedImage(newWidth, newHeight, imageType);
newImg.createGraphics().drawImage(oldImg,0,0,newWidth, newHeight,0,0,oldWidth,oldHeight, null);
then just repaint using newImg instead of the old image, should work, I'm not near a compiler at the moment to test.
http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Graphics.html#drawImage%28java.awt.Image,%20int,%20int,%20int,%20int,%20int,%20int,%20int,%20int,%20java.awt.image.ImageObserver%29

Categories

Resources