I want to put this image on top of this image.
This is my code:
public class ImageOverlayTest {
public static final String IMAGE_SOURCE_PATH = "src/main/resources/META-INF/resources/images/chess-sources/";
public static final String IMAGE_DEST_PATH = "src/main/resources/META-INF/resources/images/games/";
public static void main(String[] args) {
BufferedImage bgImage = readImage("board", "png");
BufferedImage fgImage = readImage("bb", "png");
BufferedImage overlayedImage = overlayImages(bgImage, fgImage);
writeImage(overlayedImage, "result", "png");
}
public static BufferedImage overlayImages(BufferedImage background,
BufferedImage foreground) {
Graphics2D g = background.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(background, 0, 0, null);
g.drawImage(foreground, 0, 0, null);
g.dispose();
return background;
}
public static BufferedImage readImage(String fileNameWithoutExtension, String extension) {
BufferedImage img = null;
try {
String path = IMAGE_SOURCE_PATH + fileNameWithoutExtension + "." + extension;
img = ImageIO.read(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
public static void writeImage(BufferedImage img, String fileNameWithoutExtension,
String extension) {
try {
String path = IMAGE_DEST_PATH + fileNameWithoutExtension + "." + extension;
File outputFile = new File(path);
ImageIO.write(img, extension, outputFile);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Mainly taken from here.
The result looks like this:
What is going wrong? Why is it not renderig the top image the same way as when you look at it individually? What can I do to fix that?
Something about the color profile of the background image must have been wrong. I converted it to jpg and back to png using GIMP, now it's working fine ;)
Related
I used some of the information around this site to find out to use URLs to get images into a jar file; which I want to be able to be used alone. But when I make the jar file with BlueJ, only some images show up.
Its a blackjack game, and only the table canvas shows up, while no cards ever do. Here's the code:
THIS WORKS (the table):
public class TableComponent extends JLabel{
BufferedImage table;
public TableComponent(){
URL finalTable = getClass().getResource("blackjackTableCanvas.jpg");
try {
table = ImageIO.read(finalTable);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
g2.drawImage(table, 0, 0, null);
}...}
but this does not (the cards):
public class CardRender2 extends JComponent{
BufferedImage image;
String val;
String suit;
String filename;
public CardRender2(Card card) {
this.val = card.value.face;
this.suit = card.suit.toString();
filename = this.fetchCardFileLabel();
URL cardview = getClass().getResource("\\card deck\\" + filename + ".png");
try {
image = ImageIO.read(cardview);
} catch (IOException e) {
e.printStackTrace();
}
}
public CardRender2(){
this.val = null;
this.suit = null;
filename = "DEALER_FIRST_CARD";
URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
try {
image = ImageIO.read(cardview);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
g2.drawImage(image, 0, 0, null);
}...}
my cards are in a folder in the directory I try to import into BlueJ, whereas the table is in the directory root. There are 53 cards in there (incl dealer hidden card) and I'd rather not put all of then in the root. I tried to implement them similarly. How can I do this?
looks like changing from
URL cardview = getClass().getResource("\\card deck\\DEALER_FIRST_CARD.png");
to
URL cardview = getClass().getResource("card deck/DEALER_FIRST_CARD.png");
did the trick.
I'm trying to produce PDF with visual signature and pdfbox. I have two streams and it seems that pdfbox can deal only with files. I didn't manage to make it work without three temporary files. I can see from here that API has changed, but still it deals with files.
public void signPdf(InputStream originalPdf, OutputStream signedPdf,
InputStream image, float x, float y,
String name, String location, String reason) {
File temp = null;
File temp2 = null;
File scratchFile = null;
RandomAccessFile randomAccessFile = null;
OutputStream tempOut = null;
InputStream tempIn = null;
try {
/* Copy original to temporary file */
temp = File.createTempFile("signed1", ".tmp");
tempOut = new FileOutputStream(temp);
copyStream(originalPdf, tempOut);
tempOut.close();
/* Read temporary file to second temporary file and stream */
tempIn = new FileInputStream(temp);
temp2 = File.createTempFile("signed2", ".tmp");
tempOut = new FileOutputStream(temp2);
copyStream(tempIn, tempOut);
tempIn.close();
tempIn = new FileInputStream(temp2);
scratchFile = File.createTempFile("signed3", ".bin");
randomAccessFile = new RandomAccessFile(scratchFile, "rw");
/* Read temporary file */
PDDocument document = PDDocument.load(temp, randomAccessFile);
document.getCurrentAccessPermission().setCanModify(false);
PDSignature signature = new PDSignature();
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
signature.setName(name);
signature.setLocation(location);
signature.setReason(reason);
signature.setSignDate(Calendar.getInstance());
PDVisibleSignDesigner signatureDesigner = new PDVisibleSignDesigner(
document, image, document.getNumberOfPages());
signatureDesigner.xAxis(250).yAxis(60).zoom(-90).signatureFieldName("signature");
PDVisibleSigProperties signatureProperties = new PDVisibleSigProperties();
signatureProperties.signerName(name).signerLocation(location)
.signatureReason(reason).preferredSize(0).page(1)
.visualSignEnabled(true).setPdVisibleSignature(signatureDesigner)
.buildSignature();
SignatureOptions options = new SignatureOptions();
options.setVisualSignature(signatureProperties);
document.addSignature(signature, dataSigner, options);
/* Sign */
document.saveIncremental(tempIn, tempOut);
document.close();
tempIn.close();
/* Copy temporary file to an output stream */
tempIn = new FileInputStream(temp2);
copyStream(tempIn, signedPdf);
} catch (IOException e) {
logger.error("PDF signing failure", e);
} catch (COSVisitorException e) {
logger.error("PDF creation failure", e);
} catch (SignatureException e) {
logger.error("PDF signing failure", e);
} finally {
closeStream(originalPdf);
closeStream(signedPdf);
closeStream(randomAccessFile);
closeStream(tempOut);
deleteTempFile(temp);
deleteTempFile(temp2);
deleteTempFile(scratchFile);
}
}
private void deleteTempFile(File tempFile) {
if (tempFile != null && tempFile.exists() && !tempFile.delete()) {
tempFile.deleteOnExit();
}
}
private void closeStream(Closeable is) {
if (is!= null) {
try {
is.close();
} catch (IOException e) {
logger.error("failure", e);
}
}
}
private void copyStream(InputStream is, OutputStream os) throws IOException {
byte[] buffer = new byte[1024];
int c;
while ((c = is.read(buffer)) != -1) {
os.write(buffer, 0, c);
}
is.close();
}
Apart from file madness I don't see any text on the signature. This is how result looks like:
and this is how it looks, when I do similar thing with itext library
Why name, location and reason missing from the visual signature representation? How can I fix that?
Why name, location and reason missing from the visual signature representation?
They are not there because they are not drawn.
The default way of iText to represent a visualized signature is by adding those information to the visualization.
The default way of PDFBox' PDVisibleSigBuilder to represent a visualized signature is without such information.
Neither is wrong or right, both merely are defaults.
The canonical place where people shall look for such information is the signature panel after all.
How can I fix that?
The actual contents of the signature visualization are created by a PDVisibleSigBuilder instance during signatureProperties.buildSignature():
public void buildSignature() throws IOException
{
PDFTemplateBuilder builder = new PDVisibleSigBuilder();
PDFTemplateCreator creator = new PDFTemplateCreator(builder);
setVisibleSignature(creator.buildPDF(getPdVisibleSignature()));
}
Thus, by replacing
signatureProperties.signerName(name).signerLocation(location)
.signatureReason(reason).preferredSize(0).page(1)
.visualSignEnabled(true).setPdVisibleSignature(signatureDesigner)
.buildSignature();
in your code by
signatureProperties.signerName(name).signerLocation(location)
.signatureReason(reason).preferredSize(0).page(1)
.visualSignEnabled(true).setPdVisibleSignature(signatureDesigner);
PDFTemplateBuilder builder = new ExtSigBuilder();
PDFTemplateCreator creator = new PDFTemplateCreator(builder);
signatureProperties.setVisibleSignature(creator.buildPDF(signatureProperties.getPdVisibleSignature()));
for a customized version ExtSigBuilder of this PDVisibleSigBuilder class, you can draw anything you want there, e.g.:
class ExtSigBuilder extends PDVisibleSigBuilder
{
String fontName;
public void createImageForm(PDResources imageFormResources, PDResources innerFormResource,
PDStream imageFormStream, PDRectangle formrect, AffineTransform affineTransform, PDJpeg img)
throws IOException
{
super.createImageForm(imageFormResources, innerFormResource, imageFormStream, formrect, affineTransform, img);
PDFont font = PDType1Font.HELVETICA;
fontName = getStructure().getImageForm().getResources().addFont(font);
logger.info("Added font to image form: " + fontName);
}
public void injectAppearanceStreams(PDStream holderFormStream, PDStream innterFormStream, PDStream imageFormStream,
String imageObjectName, String imageName, String innerFormName, PDVisibleSignDesigner properties)
throws IOException
{
super.injectAppearanceStreams(holderFormStream, innterFormStream, imageFormStream, imageObjectName, imageName, innerFormName, properties);
String imgFormComment = "q " + 100 + " 0 0 50 0 0 cm /" + imageName + " Do Q\n";
String text = "BT /" + fontName + " 10 Tf (Hello) Tj ET\n";
appendRawCommands(getStructure().getImageFormStream().createOutputStream(), imgFormComment + text);
logger.info("Added text commands to image form: " + text);
}
}
writes "Hello" in Helvetica at size 10 atop the lower left of the image form (the form actually displaying something).
PS: In my opinion the object oriented structure behind this should be completely overhauled.
Display the text over the signatory some time it doesn't look nice. For me, I create new image base on the text that I want to display. And merge it with the signatory image. I can add background for signatory image (company name watermark)
Here is the code create new signatory image with text and background:
public class ImageSignatory {
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("MM.dd.yyyy");
Date today = Calendar.getInstance().getTime();
String reportDate = df.format(today);
String text = "Signature eletronic Company AA DUC NGUYEN - Date " + reportDate;
String background = "background.png";
String signImage = "sign.jpg";
String textImage = createImageFromText(text);
String imageResultURL = null ;
try {
String mergedImage = mergeTwoImage(signImage, textImage);
imageResultURL = addBackgroundToImage(background, mergedImage);
} catch (Exception ex) {
}
}
public static String StringDivider(String s) {
StringBuilder sb = new StringBuilder(s);
int i = 0;
while ((i = sb.indexOf(" ", i + 30)) != -1) {
sb.replace(i, i + 1, "\n");
}
return sb.toString();
}
public static BufferedImage toBufferedImage(Image img) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
return bimage;
}
public static String addBackgroundToImage(String backgroundPATH, String imagePath) {
try {
String imageResult = "result.jpg";
Image backgroundImage = ImageIO.read(new File(backgroundPATH));
int width = backgroundImage.getWidth(null);
int height = backgroundImage.getHeight(null);
Image signAndText = ImageIO.read(new File(imagePath));
signAndText = signAndText.getScaledInstance(width, height, Image.SCALE_SMOOTH);
signAndText = toBufferedImage(signAndText);
BufferedImage combined = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g2 = combined.getGraphics();
g2.drawImage(backgroundImage, 0, 0, null);
g2.drawImage(signAndText, 0, 0, null);
g2.dispose();
ImageIO.write(combined, "JPG", new File(imageResult));
return imageResult;
} catch (IOException ex) {
return null;
}
}
public static String mergeTwoImage(String first, String second) {
try {
String tempFileName = "merged_image.png";
Image signatoryImage = ImageIO.read(new File(first));
Image addtionalTextImage = ImageIO.read(new File(second));
float ratio = (float) signatoryImage.getWidth(null) / (float) addtionalTextImage.getWidth(null);
addtionalTextImage = addtionalTextImage.getScaledInstance((int) (ratio * (float) addtionalTextImage.getWidth(null)), (int) (ratio * (float) addtionalTextImage.getHeight(null)), Image.SCALE_SMOOTH);
addtionalTextImage = toBufferedImage(addtionalTextImage);
BufferedImage combinedTemp = new BufferedImage(signatoryImage.getWidth(null), signatoryImage.getHeight(null) + (int) (ratio * (float) addtionalTextImage.getHeight(null)), BufferedImage.TYPE_INT_ARGB);
Graphics g = combinedTemp.getGraphics();
g.drawImage(signatoryImage, 0, 0, null);
g.drawImage(addtionalTextImage, 0, signatoryImage.getHeight(null), null);
g.dispose();
ImageIO.write(combinedTemp, "PNG", new File(tempFileName));
return tempFileName;
} catch (IOException ex) {
return null;
}
}
public static String createImageFromText(String text) {
String tempFileName = "text.png";
text = StringDivider(text);
String[] textParts = text.split("\n");
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
Font font = new Font("Arial", Font.PLAIN, 48);
g2d.setFont(font);
FontMetrics fm = g2d.getFontMetrics();
int width = 0;
for (String textPart : textParts) {
int tempWidth = fm.stringWidth(textPart);
if (tempWidth > width) {
width = tempWidth;
}
}
width += 10;
int oneLineHeight = fm.getHeight();
int height = (oneLineHeight) * textParts.length;
g2d.dispose();
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
g2d = img.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.setFont(font);
fm = g2d.getFontMetrics();
g2d.setColor(Color.BLACK);
int index = 0;
for (String textPart : textParts) {
g2d.drawString(textPart, 5, (oneLineHeight) * index + fm.getAscent());
index++;
}
g2d.dispose();
try {
ImageIO.write(img, "PNG", new File(tempFileName));
} catch (IOException ex) {
return null;
}
return tempFileName;
}
public static void removeFile(String fileName) {
try {
File file = new File(fileName);
file.delete();
} catch (Exception ex) {
}
}
}
I have aplication where I drawing object by canvas. And I want saving this pictures like image. For example bmp, or jpg to folder. How can I do it ? Here is bite of my code.
public class hell extends View{
public static int width= aktivita.width;
public static int koeficient = 5;
final Paint mPaint;
public static int t;
public boolean filter = true;
static ArrayList<Circle> mCircles;
private static boolean Kontroler = true;
public void draw(Canvas canvas) {
Paint p = new Paint();
p.setColor(Color.RED);
kres(canvas);
invalidate();
}
}
public krouzky(Context context, AttributeSet atrs) {
super(context, atrs);
mMalovani = new Paint();
mMalovani.setColor(Color.RED);
mMalovani.setAntiAlias(true);
createCircles();
}
Adding objects for draw
public static void Prid() {
int ran = aktivita.width/8;
mCircles.add(new Circle(80, 200, ran));
}
Make arrayList
private static void createCircles() { if (mCircles == null) { mCircles = new ArrayList<Circle>(); }
int r = aktivita.width/8;
mCircles.add(new Circle(80, 200, r));
}
Drawing object
private void kres(Canvas canvas) {
for (Circle c : mCircles) {
//
canvas.drawCircle(c.getCurrentX(), c.getCurrentY(), c.getRadius(),
mPaint);
}
}
I tried this, but after start with button click loadBitmapFromView(v);
save();
my program shut down, and in SD card is file with .png suffix. But It have 0 bites, and I´t open it.
public static Bitmap loadBitmapFromView(View view) {
// width measure spec
int widthSpec = View.MeasureSpec.makeMeasureSpec(
view.getMeasuredWidth(), View.MeasureSpec.AT_MOST);
// height measure spec
int heightSpec = View.MeasureSpec.makeMeasureSpec(
view.getMeasuredHeight(), View.MeasureSpec.AT_MOST);
// measure the view
view.measure(widthSpec, heightSpec);
// set the layout sizes
view.layout(view.getLeft(), view.getTop(), view.getMeasuredWidth() + view.getLeft(), view.getMeasuredHeight() + view.getTop());
// create the bitmap
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
// create a canvas used to get the view's image and draw it on the bitmap
Canvas c = new Canvas(bitmap);
// position the image inside the canvas
c.translate(-view.getScrollX(), -view.getScrollY());
// get the canvas
view.draw(c);
return bitmap;
}
public void save(){
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
// generate the image path
String imagePath = Environment.getExternalStorageDirectory().toString() + File.separator + fileName + ".png";
try {
// save the image as png
FileOutputStream out = new FileOutputStream(imagePath);
View view = null;
// compress the image to png and pass it to the output stream
loadBitmapFromView(view).compress(Bitmap.CompressFormat.PNG, 90, out);
// save the image
out.flush();
out.close();
} catch (Exception error) {
Log.e("Error saving image", error.getMessage());
}
}
To get a bitmap from a View:
public static Bitmap getBitmapFromView(View view) {
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
To save it to SD Card:
public void saveImage(Bitmap b)
{
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "XXXXXXXXXXX.jpg");
fOut = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
You can do just the insert in MediaStore, but it will loose quality. This way the compression is done with the quality you want.
EDIT:
Added some logging to help figure out why you're getting the FileNotFound exception:
public void saveImage(Bitmap b)
{
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "XXXXXXXXXXX.jpg");
Log.d("saveImage", "File to save: " + file.getAbsolutePath());
try {
FileOutputStream fOut = new FileOutputStream(file);
}
catch(FileNotFoundException e) {
Log.d("saveImage", "Couldn't open file: " + e.getMessage());
}
if(fOut != null) {
b.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
}
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
How do i save a resized image to a specific folder?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
ImgChooser ic = new ImgChooser();
ImageIcon icon = new ImageIcon(me,"id pic");
Image img1 = icon.getImage();
Image img2 = img1.getScaledInstance(105, 105, 0);
icon.setImage(img2);
jLabel1.setIcon(icon);
}
This first code is where i get the image and resize it. Then i want the resized image to be saved in another folder. Thanks in advance
Use ImageIO.write(...) as others have already said (+1 to them), to add here is an example for you:
public static void main(String[] args) {
try {
BufferedImage originalImage = ImageIO.read(new File("c:\\test.jpg"));//change path to where file is located
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type, 100, 100);
ImageIO.write(resizeImageJpg, "jpg", new File("c:\\images\\testresized.jpg")); //change path where you want it saved
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private static BufferedImage resizeImage(BufferedImage originalImage, int type, int IMG_WIDTH, int IMG_HEIGHT) {
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
return resizedImage;
}
Reference:
http://www.mkyong.com/java/how-to-resize-an-image-in-java/
Try this...
Use ImageIO.write() method...
static boolean ImageIO.write(RenderedImage im, String formatName, File output) throws IOException
Eg:
try {
// retrieve image
BufferedImage bi = getMyImage();
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
...
}
First transform your image into a BufferedImage and then use ImageIO to save the image:
BufferedImage image = new BufferedImage(img2.getWidth(null), img2.getHeight(null), BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2 = image.createGraphics();
g2.drawImage(img2, 0, 0, null);
g2.dispose();
ImageIO.write(image, formatName, outputFile);
Where the format name is a String like "jpg", "png" or "gif" and outputFile is the File to save the image to.
Also please note that if you are saving an image that doesn't support an alpha level (transparency) then the third parameter you pass to the BufferedImage constructor should be a 3 byte image like: BufferedImage.TYPE_3BYTE_BGR