Image resizing using imgscalr API in java - java

How to convert Buffered image into a file object.
My function actually needs to return a file object . The imgscalr resizing function returns a BufferedImage after resizing.so How to convert it into a file object.

Here is an example of writing to a PNG file:
ImageIO.write(yourImage, "PNG", "yourfile.png");
You must import ImageIO (javax.imageio) first, however.
Then you can get the File object for the image with new File("yourfile.png");.
You could put this in a function for ease of use; here is an example:
public File imageToFile(BufferedImage img, String fileName) {
if (!(fileName.endsWith(".png"))) fileName += ".png";
ImageIO.write(img, "PNG", filename);
return new File(fileName);
}
Here is a link to the docs.
You cannot make a file object without saving... well, a file. You could put it in a temporary directory and delete it when you are done using it, though.

Related

Java getResourceAsStream is loading a previous version of desired file but not the most recently created file

Hi I'm following this tutorial, to load an image I created, on my webpage.
Here's the code I use to load the image
#GetMapping(
value="/download",
produces = MediaType.IMAGE_JPEG_VALUE
)
public #ResponseBody byte[] getDownload() throws IOException{
InputStream in = getClass().getResourceAsStream("/static/images/collage.jpeg");
return IOUtils.toByteArray(in);
}
Here's how I create the collage.jpeg file
// delete previous file
File file = new File("src/main/resources/static/images/collage.jpeg");
if(file.exists())
file.delete();
// Write the collage to a the desired file.
ImageIO.write(collage, "jpeg", file);
The issue I'm having is that when I access the /download endpoint it's retrieving the most previous version of collage.jpeg and not the most recently created one. collage is a BufferedImage object which I use ImageIO to write to the directory.
Can anyone explain to me why this is happening and what I can do to fix it?
Thanks.

IOException: StreamClosed Without Apparent Cause

I have created a program in Java that I want packaged into an executable jar file. I want this program to take images from the jar file and display them. I created an abstract class with a method to take a String filename and return an Image object. However, when I try to run this method, it fails and produces an "IOException: Stream closed" error.
I can't find anything on why the stream is closed. I don't have any other input streams in my program, as far as I know. Using the method in a new main with nothing but a JFrame set-up still produces the same error.
Whether I call the image file only by its name (i.e. "example.png") or use its relative path (i.e. "/src/icons/example.png"), OR use its absolute path (i.e. "C:/Users/My_Name/Desktop/EXAMPLE/src/icons/example.png") I receive the same stream closed error.
public static Image importImage(String fileName) throws IOException {
Image img = null;
byte[] data = new byte[10000];
BufferedInputStream bis = new BufferedInputStream( Thread.currentThread().getClass().getResourceAsStream(fileName));
int byteRead = bis.read(data, 0, 10000);
img = Toolkit.getDefaultToolkit().createImage(data);
return img;
}
I expect the program to accept the name of the image file in question, and return an Image object. The image file is on the project's classpath, and should be visible.
Okay. So as it turns out, a method like this has two requirements: One, you have to call 'thisClassName.class.getResourceAsStream(fileName).' Exactly like that. You also need to have your fileName start with '/' or it will completely not work. But, as long as the resources you are looking for are included in your program's classpath, it should work from there.

How to write image in wsq format?

I am using the following code:
OutputStream outputfile = new FileOutputStream("resource/LeftIndexSegmentMy.WSQ");
ImageIO.write(subImage,"WSQ", outputfile);
However, the resulting file is empty. No image is there.
So, how do I write an image in the WSQ format?

Write animated-gif stored in BufferedImage to java.io.File Object

I am reading a gif image from internet url.
// URL of a sample animated gif, needs to be wrapped in try-catch block
URL imageUrl = new Url("http://4.bp.blogspot.com/-CTUfMbxRZWg/URi_3Sp-vKI/AAAAAAAAAa4/a2n_9dUd2Hg/s1600/Kei_Run.gif");
// reads the image from url and stores in BufferedImage object.
BufferedImage bImage = ImageIO.read(imageUrl);
// creates a new `java.io.File` object with image name
File imageFile = new File("download.gif");
// ImageIO writes BufferedImage into File Object
ImageIO.write(bImage, "gif", imageFile);
The code executes successfully. But, the saved image is not animated as the source image is.
I have looked at many of the stack-overflow questions/answers, but i am not able to get through this. Most of them do it by BufferedImage frame by frame which alters frame-rate. I don't want changes to the source image. I want to download it as it is with same size, same resolution and same frame-rate.
Please keep in mind that i want to avoid using streams and unofficial-libraries as much as i can(if it can't be done without them, i will use them).
If there is an alternative to ImageIO or the way i read image from url and it gets the thing done, please point me in that direction.
There is no need to decode the image and then re-encode it.
Just read the bytes of the image, and write the bytes, as is, to the file:
try (InputStream in = imageUrl.openStream()) {
Files.copy(in, new File("download.gif").toPath());
}

Encoding image file

I have an int array of color r,g and b values. And I would like to encode them in a image file. Is there an easy method in android to write this data to an image? Also which image format should I use for this, png?
Create a bitmap using your int array like this using Bitmap.createBitmap:
int[] array; // array of int RGB values e.g. 0x00ff0000 = red
Bitmap bitmap = Bitmap.createBitmap(array, width, height, Bitmap.Config.ARGB_8888);
Then write it out using Bitmap.compress:
outStream = new FileOutputStream(filepath);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
You can call Environment.getExternalStorageDirectory() to get a folder on external storage where you can save the file, if that's where you want to save it. You can get the path with get File.getAbsolutePath(), e.g:
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/image.png";
You need the WRITE_EXTERNAL_STORAGE permission defined in your AndroidManifest.xml to be able to write to files on external storage.
There are pure java implementations for reading and writting images:
Image processing library for Android and Java
Probably some will work in android out of the box
I believe ImageIO is available in Android. The ImageIO API provides methods to read the source image and to write the image in the new file format.
To read the image, simply provide the ImageIO.read() method a File object for the source image. This will return a BufferedImage.
//Create file for the source
File input = new File("c:/temp/image.bmp");
//Read the file to a BufferedImage
BufferedImage image = ImageIO.read(input);
Once you have the BufferedImage, you can write the image as a PNG. You will need to create a File object for the destination image. When calling the write() method, specify the type string as "png".
//Create a file for the output
File output = new File("c:/temp/image.png");
//Write the image to the destination as a PNG
ImageIO.write(image, "png", output);

Categories

Resources