How to save an image in a set location? - java

I am trying to save a resized picture to the user's desktop but not sure how to do that.
Here's my code so far:
mi.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String userhome = System.getProperty("user.home");
fileChooser = new JFileChooser(userhome + "\\Desktop");
fileChooser.setAutoscrolls(true);
switch (fileChooser.showOpenDialog(f)) {
case JFileChooser.APPROVE_OPTION:
BufferedImage img = null;
try {
img = ImageIO.read(fileChooser.getSelectedFile());
} catch (IOException e1) {
e1.printStackTrace();
}
Image dimg = img.getScaledInstance(f.getWidth(),
f.getHeight(), Image.SCALE_SMOOTH);
path = new ImageIcon(dimg);
configProps.setProperty("Path", fileChooser
.getSelectedFile().getPath());
imBg.setIcon(path);
break;
}
}
});
The code above resizes the imaged selected to fit the size of the JFrame then sets it to the JLabel.
This all works well but I also want to output the file to a set location lets say to the users desktop to make it easier. I'm currently looking at output stream but can't quite get my head around it.
Any help would be great.

Get the current Icon from the JLabel...
Icon icon = imgBg.getIcon();
Paint the icon to a BufferedImage...
BufferedImage img = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();
Save the image to a file...
ImageIO.write(img, "png", new File("ResizedIcon.png"));
(and yes, you could use a JFileChooser to pick the file location/name)
You should also take a look at this for better examples of scaling an image, this way, you could scale the BufferedImage to another BufferedImage and save the hassle of having to re-paint the Icon
You might also like to take a look at Writing/Saving an Image

This is a example which is about saving images from Web to the local.
package cn.test.net;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageRequest {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
//a url from web
URL url = new URL("http://img.hexun.com/2011-06-21/130726386.jpg");
//open
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//"GET"!
conn.setRequestMethod("GET");
//Timeout
conn.setConnectTimeout(5 * 1000);
//get data by InputStream
InputStream inStream = conn.getInputStream();
//to the binary , to save
byte[] data = readInputStream(inStream);
//a file to save the image
File imageFile = new File("BeautyGirl.jpg");
FileOutputStream outStream = new FileOutputStream(imageFile);
//write into it
outStream.write(data);
//close the Stream
outStream.close();
}
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
//every time read length,if -1 ,end
int len = 0;
//a Stream read from buffer
while( (len=inStream.read(buffer)) != -1 ){
//mid parameter for starting position
outStream.write(buffer, 0, len);
}
inStream.close();
//return data
return outStream.toByteArray();
}
}
Hope this is helpful to you!

Related

Image Resolution is decrease wile downloading Image to local machine using Java code

I am trying to download High resolution Image from URL using Java Code.
but after download to local machine, the resolution of image is decrease.
I am using below code to download, can anybody suggest me where I am making mistake.
String url = "https://s3.eu-central-1.amazonaws.com/euroc-inspect/processing/E1039585_TOP_3_1.jpg";
URL liveUrl = new URL(url);
BufferedImage bimg = ImageIO.read(liveUrl);
int width = bimg.getWidth();
int height = bimg.getHeight();
ImageIO.write(bimg, "jpg", new File("E:/img.jpg"));
System.out.println("Image Saved");
Getting the exact same resolution:
2048x1425
ImageDownloader.java:
import java.net.URL;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
public class ImageDownloader {
public static void main(String[] args) throws Exception{
if(args.length<2) {
System.out.println("Usage: ImageDownloader <url> <localfilename>");
System.exit(1);
}
String url = args[0] ;
String targetFile = args[1];
URL liveUrl = new URL(url);
BufferedImage bimg = ImageIO.read(liveUrl);
int width = bimg.getWidth();
int height = bimg.getHeight();
ImageIO.write(bimg, targetFile.substring(targetFile.indexOf(".")), new File(targetFile));
System.out.printf("Image %s saved. (size: %dx%d)",targetFile, width, height);
}
}
original image

Write text on image and convert into pdf in java?

I want to create a PDF using image and some text. here image used as mask and text set on different spatial place.
I already generate pdf using image but cannot write text on it.
Here is the image
And output
My code
import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import javax.swing.JFileChooser;
public class Test {
public static void main(String[] args) {
Document document = new Document(PageSize.A4_LANDSCAPE, 0, 0, 0, 0);
String input = "src/icon/orginal_pad.jpg"; // .gif and .jpg are ok too!
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
String filePath = fileChooser.getSelectedFile().getPath();
try {
FileOutputStream fos = new FileOutputStream(filePath);
PdfWriter writer = PdfWriter.getInstance(document, fos);
writer.open();
document.open();
Image im = Image.getInstance(input);
im.scaleToFit(PageSize.A4_LANDSCAPE.getWidth(), PageSize.A4_LANDSCAPE.getHeight());
document.add(im);
//code here
document.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Bengali Joint letters in Kalpurush font in java messed up

I have written a program (collecting from various sources, I am a beginner) in Java that takes a text(bengali) written in a .txt file and converts it to a .bmp image using the drawString function. The code is :
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.util.*;
import java.awt.font.*;
import java.awt.geom.*;
class TextToImageDemo
{
public static void main(String[] args) throws IOException
{
String sampleText = "আমার",s="নাম";
BufferedReader br = null;
for (int u=1;u<=9;u++)
{
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("E:\\Java\\bengtext\\f2-0"+u+".txt")),"UTF-8"));
while ((sampleText = br.readLine()) != null)
{
System.out.println(sampleText);
s=sampleText;
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)br.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
//Image file name
String fileName = "Image";
//create a File Object
File newFile= new File("./" + fileName + ".jpeg");
//create the font you wish to use
Font font = new Font(/*Lohit Bengali*/"Kalpurush", Font.PLAIN, 50);
//create the FontRenderContext object which helps us to measure the text
FontRenderContext frc = new FontRenderContext(null, true, true);
//create a BufferedImage object
BufferedImage image = new BufferedImage(2000, 200, BufferedImage.TYPE_INT_RGB);
//calling createGraphics() to get the Graphics2D
Graphics2D g = image.createGraphics();
System.out.println(s);
//set color and other parameters
g.setColor(Color.WHITE);
g.fillRect(0, 0, 2000, 200);
g.setColor(Color.BLACK);
g.setFont(font);
FontMetrics fm=g.getFontMetrics();
Rectangle r=new Rectangle(fm.getStringBounds(s, g).getBounds());
String d=s.substring(1,s.length());
g.drawString(d, image.getWidth()/2-r.width/2, image.getHeight()/2+r.height/2);
//releasing resources
g.dispose();
try
{
FileOutputStream fos = new FileOutputStream("E:\\Java\\bengtext\\f2-0"+u+".bmp");
ImageIO.write(image,"bmp",fos);
fos.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
}
My main problem lies in the fact that a text like
দ্বিতীয়তা , একাগ্রতা , " জ্ঞান আহরনের একটি মাত্র উপায়
is formed like
How can this be solved?
Edit:
On checking all the 263 fonts available , I found only 6 of them were able to display bengali somewhat correctly. But in everyone of them the problem with the joint words lie as shown in the above picture. So question is : What is the exact problem happening here? Is JAVA not being able to read the joint words correctly, or is it not being able to draw them correctly ?
And secondly , how to make java draw the joint words correctly?

How to read a GIF with Java's ImageIO and preserve the animation?

I'm working on a project and the goal is to have all images read with ImageIO. This seems to work for everything except GIF images (which display as a static image of the initial frame). I have seen other answers on Stack Overflow and from a thread on the Oracle forums but most require using Java's File class which I can't access due to the program's SecurityManager. I've been able to break the GIF down into an Image array and edit the metadata, but after stitching everything back together I can only display a single image.
Below is a SSCCE for the program:
import java.awt.Image;
import java.awt.Toolkit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GifRenderer {
public static void main(String[] args) throws Exception {
Image image = null;
byte[] imageByteArray = null;
try {
String location = "http://i.imgur.com/Ejh5gJa.gif";
imageByteArray = createByteArray(location);
// This works, but I'm trying to use ImageIO
//image = Toolkit.getDefaultToolkit().createImage(imageByteArray);
InputStream in = new ByteArrayInputStream(imageByteArray);
image = ImageIO.read(in);
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.setSize(300, 300);
JLabel label = new JLabel(new ImageIcon(image));
frame.add(label);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// Constraint: This method simulates how the image is originally received
private static byte[] createByteArray(String urlString) throws IOException {
URL url = new URL(urlString);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096];
int n;
while ( (n = is.read(byteChunk)) > 0 ) {
baos.write(byteChunk, 0, n);
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
if (is != null) { is.close(); }
}
return baos.toByteArray();
}
}
Some constraints worth mentioning that might not be clear:
The image is originally received as a byte array
The image should be read by ImageIO
The final result should be an Image object
The File class can't be accessed
Given these constraints is there still a way to use ImageIO to display the GIF the same way Toolkit.getDefaultToolkit().createImage() would display the image?

ImageIcon update in Java (from the internet)?

I have some URL with an image there. This image updates during each request (that is, each request to the (same) URL returns a new image). Say, this URL points to CAPTCHA.
My goal is to load and display several such images in my program.
The following code loads these images to my local filesystem and works OK (that is, all the images are different, unique):
String filePath;
String urlPath;
int numOfFilesToDownload;
//Here filePath and urlPath are initialized.
//filePath points to the directory, where to save images
//urlPath is the url from where to download images
//numOfFilesToDownload is the number of files to download
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing connection
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Downloading image
try(InputStream is = conn.getInputStream();
FileOutputStream os = new FileOutputStream(filePath + "img" + i + ".jpg")){
int b;
while((b = is.read()) != -1)
os.write(b);
}
}
But something weird happens, when I try the following thing:
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing image from the url
URL url = new URL(urlPath);
javax.swing.ImageIcon ico = new javax.swing.ImageIcon(url);
//Showing the graphical dialog window with the image
javax.swing.JOptionPane.showMessageDialog(null, ico);
}
In the latter case, each dialog contains the same image, namely the one, downloaded during the very first iteration.
Also, the experiments show, that if you concatenate "?r=" to the urlPath (that is, a simple GET request parameter), the url will still be valid.
And the following code appears to be valid and does exactly what it has (namely each image shown is different from the previous):
for(int i = 0; i < numOfFilesToDownload; i++){
//Initializing image from the url
URL url = new URL(urlPath + "?r=" + i);
javax.swing.ImageIcon ico = new javax.swing.ImageIcon(url);
//Showing the graphical dialog window with the image
javax.swing.JOptionPane.showMessageDialog(null, ico);
}
Hence I can make a conclusion, that ImageIcon somehow remembers the URLs it handled and simply does not bother to perform the same work twice... Why and how? There's nothing in javadocs about it.
When I tried a variation of your code, it worked fine. My SSCCE:
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class TestUrls {
public static final String BASE_URL_PATH = "http://static.ed.edmunds-media.com/" +
"unversioned/adunit/homepage_showcase/";
public static final String[] URL_PATHS = {
"honda-odyssey-2013.png",
"chevrolet-impala-2013.png",
"mazda-cx9-2013.png",
"toyota-rav4-2013-2.png"
};
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
for (String urlPath : URL_PATHS) {
String fullUrlPath = BASE_URL_PATH + urlPath;
try {
URL url = new URL(fullUrlPath);
BufferedImage img = ImageIO.read(url);
ImageIcon icon = new ImageIcon(img);
JOptionPane.showMessageDialog(null, icon);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
}

Categories