Drawing a resource image on to a buffered image - java

Okay, I want to create a copy of an image I have in my resource folder, and put it onto the desktop pretty much. Example: My project has a resource folder with an image called apple.png. Since when I export my jar file it can't find it, I want to copy it to the desktop so it can find it from there. Here is what I tried doing:
try {
// retrieve image
BufferedImage bi = new BufferedImage(256, 256,
BufferedImage.TYPE_INT_RGB);
File outputfile = new File(
"C:/Users/Owner/Desktop/saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
}
}
This just created the buffered Image for me on my desktop. How do I take my res Image and copy it to it.

Any reason for loading it as an image? If you just want to copy resource to desktop without changing it:
InputStream resStream = getClass().getResourceAsStream("/image.png"));
//Improved creation of output path:
File path = new File(new File(System.getProperty("user.home")), "Desktop");
File outputFile = new File(path, "saved.png");
//now write it
Files.copy(resStream, outputFile);

You need to load the BufferedImage as the image file.
BufferedImage bi = ImageIO.read(new File(getClass().getResource("/apple.png"));));
All the other steps are the same.

Related

Copying image and maintain orientation?

Edit
It turns out that the 2nd snippet is actually working but the images in question still show incorrectly in my IDE (IntelliJ IDEA) for some reason.
I am trying read an image, place a watermark and save it in a different folder and the below code does a good job, but it randomly orientates my images.
try {
final Image image = ImageIO.read(file);
int w = ((BufferedImage) image).getWidth();
int h = ((BufferedImage) image).getHeight();
final BufferedImage finalImage =
new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
//Graphics2D g = finalImage.createGraphics();
Graphics2D g = (Graphics2D) finalImage.getGraphics();
g.drawImage(image, 0, 0, null);
g.drawImage(watermark, 0, 0, null);
g.dispose();
File outputFile = new File("watermarked/" + folderName + "/" + file.getName());
outputFile.mkdirs();
ImageIO.write(finalImage, "jpg", outputFile);
} catch (IOException e) {
// TODO: notify client
e.printStackTrace();
}
After some reading I learned that ImageIO.read(...) does not maintain orientation or other "metadata" of the image it is processing. I also read about using the ImageReader to extract the metadata. According to the docs, using ImageReader.readall() should include the metadata in the returned IIOImage but I still end up with some of my images upside down. The below code demonstrates the copying without adding a watermark.
File out = new File("watermarked/" + folderName + "/" + file.getName());
out.getParentFile().mkdirs();
ImageInputStream input = ImageIO.createImageInputStream(file);
ImageOutputStream output = ImageIO.createImageOutputStream(out);
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
ImageReader reader = readers.next();
reader.setInput(input);
IIOImage image = reader.readAll(0, null);
// Should not be needed since readAll should already take care of it.
IIOMetadata metadata = reader.getImageMetadata(0);
image.setMetadata(metadata);
ImageWriter writer = ImageIO.getImageWriter(reader);
writer.setOutput(output);
writer.write(image);
System.out.println(writer.canReplaceImageMetadata(0)); // Returns false
writer.replaceImageMetadata(0, metadata); // Results in a "Unsupported write variant" error.
Both code snippets reside in a method that get passed a folderName as a string and the actual image file.
Edit
The above snippet works and the issue is something else. In my windows folder all my images made with a Galaxy S8 show in the correct orientation. But when I copy them to my project and open them in IntelliJ IDEA some are oriented differently. So I added sanselan as a dependency to get more insight in the meta data of the images and the images that get a different orientation in the IDE do indeed show a different orientation in the metadata. But why aren't they oriented like that in the windows folder, am I missing a metadata field or is windows storing additional data somewhere outside the image metadata?

Outputting Image in java

I have made a program in java that accepts a color image and converts it into gray scale image. The image is read as a BufferedImage, the RGB components are extracted and modified and set into the same image to display on the console window created. But I want the output as a separate jpeg or png file. Can someone tell me how to do this?
EDIT:
public static void saveToFile(BufferedImage img)throws FileNotFoundException, IOException
{
File outputfile = new File("E:\\Java\\Sample.jpg");
ImageIO.write(img, "jpg", outputfile);
}
This was the method I was hoping to use .Here img was the image I was using(editing upon, i.e. changing pixel values).And the path where I want to store my output was E:\Java . Please Someone help..
use this way:
{
File outputfile = new File("E:\\Java\\Sample.jpg");
FileOutputStream fos = new FileOutputStream(outputfile);
ImageIO.write(img, "jpg", outputfile);
fos.flush();
fos.close()
}

Java application saves image on project folder instead of eclipse folder

I'm trying to save an image file to my project folder.
Image file comes from database.
It is a maven project and rest web service.
I don't have any servlets.
Here is my code, but it saves on eclipse folder.
byte[] imgData = null;
Blob img = null;
img = resultset.getBlob("LOGO");
imgData = img.getBytes(1, (int) img.length());
BufferedImage img2 = null;
img2 = ImageIO.read(new ByteArrayInputStream(imgData));
File outputfile = new File("birimler/"+resultset.getString("BASLIK")
+ "Logo.png");
outputfile.mkdirs();
ImageIO.write(img2, "png", outputfile);
System.out.println(outputfile.getAbsolutePath());
Output is: /Users/xxx/Documents/eclipse/Eclipse.app/Contents/MacOS/birimler/imageLogo.png
Thanks for help!
Thats because eclipse working dir is his installation folder.
Provide a full absolute path, or change the working dir of your run configuration.
File outputfile = new File("/birimler/"+resultset.getString("BASLIK")
+ "Logo.png");
Would end up in
"/birimler/imageLogo.png"
And adding one more slash:
File outputfile = new File("/birimler/"+resultset.getString("BASLIK")
+ "/Logo.png");
would produce:
"/birimler/image/Logo.png"

Load image from a filepath via BufferedImage

I have a problem with Java application, particular in loading a image from a location in my computer.
Following this post I used a BufferedImage and a InputFileStream to load an image on my computer. First, I put the image (pic2.jpg) into the source code and that is working. However, if I put the image to another place (let's say C:\\ImageTest\pic2.jpg), Java IDE show me an IllegalArgumentException
return ImageIO.read(in);
here is the code:
public class MiddlePanel extends JPanel {
private BufferedImage img;
public MiddlePanel(int width) {
//img = getImage("pic2.jpg");
img = getImage("C:\\ImageTest\\pic2.jpg");
this.setPreferredSize(new Dimension(800,460));
}
public void paintComponent(Graphics g) {
// ...
}
private BufferedImage getImage(String filename) {
// This time, you can use an InputStream to load
try {
// Grab the InputStream for the image.
InputStream in = getClass().getResourceAsStream(filename);
// Then read it.
return ImageIO.read(in);
} catch (IOException e) {
System.out.println("The image was not loaded.");
//System.exit(1);
}
return null;
}
}
To read an .jpg file from non-relative path you could use this:
BufferedImage img = null;
try
{
img = ImageIO.read(new File("C:/ImageTest/pic2.jpg")); // eventually C:\\ImageTest\\pic2.jpg
}
catch (IOException e)
{
e.printStackTrace();
}
I do not have any Java environment at the moment, so hope it works and is written correctly.
getResource & getResourceAsStream do not work with file paths, but paths relative the code base. If the code base is C: then a relative path that would locate the resource is /ImageTest/pic2.jpg.
..difference between load file by FileInputStream and getResourceAsStream?
One major difference is that the getResource.. will work with a resource inside a Jar, which is no longer a File. Therefore FileInputStream cannot be used to access such a resource.
You cannot use Class#getResource(String) or Class#getResourceAsStream(String) in this case. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. If this object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String).
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
If the name begins with a / (\u002f), then the absolute name of the resource is the portion of the name following the /.
Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with / substituted for . (\u002e).
Generally, it is not a good thing to hard code the system location of your resources in your code. The neat and clean way is to put your resources in your classpath and access them. Hope this clarifies why it's not working
//This code snippet read an image from location on the computer and writes it to a different location on the disk
try {
byte[] imageInByte;
BufferedImage imageOnDisk = ImageIO.read(new File("C:\\ImageTest\\pic2.jpg"));
//Create a ByteArrayOutputStrea object to write image to
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//Write the image to the OutputStream
ImageIO.write(imageOnDisk, "jpg", baos);
baos.flush();
//Initialise the byte array object with the image that was written to the OutputStream
imageInByte = baos.toByteArray();
baos.close();
// convert byte array back to BufferedImage
InputStream in = new ByteArrayInputStream(imageInByte);
BufferedImage bImageFromConvert = ImageIO.read(in);
//write the image to a new location with a different file name(optionally)
ImageIO.write(bImageFromConvert, "jpg", new File(
"c:\\index.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
To find the image Width, height and size
BufferedImage image = null;
int imageWidth = -1;
int imageHeight = -1;
int fileSize = -1;
try {
File imageFile = new File(imagePath);
int fileSize = (int) imageFile.length();
image = ImageIO.read(imageFile); // Reading the Image from the file system
imageWidth = image.getWidth();
imageHeight = image.getHeight();
} catch (IOException e) {
e.printStackTrace();
}

Add image to PDF from a URL?

Im trying to add a image from a URL address to my pdf. The code is:
Image image=Image.getInstance("http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif");
image.scaleToFit((float)200.0, (float)49.0);
paragraph.add(image);
But it does not work. What can be wrong?
This is a known issue when loading .gif from a remote location with iText.
A fix for this would be to download the .gif with Java (not via the getInstance method of iText's Image class) and to use the downloaded bytes in the getInstance method of the Image class.
Edit:
I went ahead and fixed remote gif loading in iText, it is included from iText 5.4.1 and later.
Adding Image into Itext PDF is not possible through URL .
Only way to add image in PDF is download all images in to local directory and apply below code
String photoPath = Environment.getExternalStorageDirectory() + "/abc.png";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap b = BitmapFactory.decodeFile(photoPath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap.createScaledBitmap(b, 10, 10, false);
b.compress(Bitmap.CompressFormat.PNG, 30, stream);
Image img = null;
byte[] byteArray = stream.toByteArray();
try {
img = Image.getInstance(byteArray);
} catch (BadElementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The way you have used to add images to IText PDF is the way that is used for adding local files, not URLs.
For URLs, this way will solve the problem.
String imageUrl = "http://www.google.com/intl/en_ALL/"
+ "images/logos/images_logo_lg.gif";
Image image = Image.getInstance(new URL(imageUrl));
You may then proceed to add this image to some previously open document, using document.add(image).
For further reference, please visit the [Java IText: Image docs].

Categories

Resources