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

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());
}

Related

How can I add a profile picture to a user in liferay using java?

I wish to create a new user programmatically and giving this user a portrait. I'm using a csv file, to loop through my code, which has a number of entries. Their fullname, their email adres and a url which links to an image is all in this csv file.
The users are made but they don't get a profile picture, however if i use a path to my local machine it works just fine. Is there a way i can use a url and save the image as an object in java?
My code so far using a local file:
// Getting image from local path
File sourceImage = new File("C:\\Users\\path_to_image");
BufferedImage img = ImageIO.read(sourceImage);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
byte[] bytes = baos.toByteArray();
// Adding profile picture to newly made user
UserLocalServiceUtil.updatePortrait(user.getUserId(), bytes);
I do not want to have to download the pictures because there are quite a lot of them, but if that is the only way I'll have to of course.
Any help would be much appreciated!

Exception on sending big files through java sockets

I'm creating a Chat in java for a university project, and one of the requirements is each user must have an image associate, this can be done through registration windows and data modification windows, in registration everything works great, but on the modification window, the program throws an exception when i try to send big files, both codes (registration and modification) are basiccally the same, changing only variables and path, but still gives my problem only in modification
Here is my code:
Client:
BufferedImage image = ImageIO.read(new File(usuario.getImagen().getCanonicalPath()));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", byteArrayOutputStream);
byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
salida.write(size);
salida.write(byteArrayOutputStream.toByteArray());
salida.flush();
Server:
dir = new File ("." + "/Documentos/Imagenes de Verificacion/" +
usuarioRegistro.getNombreDeUsuario() + ".jpg");
sizeAr = new byte[4];
entrada.read(sizeAr);
size = ByteBuffer.wrap(sizeAr).asIntBuffer().get();
imageAr = new byte[size];
entrada.readFully(imageAr);
image = ImageIO.read(new ByteArrayInputStream(imageAr));
ImageIO.write(image, "jpg", new File(dir.getCanonicalPath()));
usuarioRegistro.setImagen(dir.getCanonicalFile());
And the exception is:
Exception in thread "Thread-0" java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at javax.imageio.ImageIO.getWriter(ImageIO.java:1591)
at javax.imageio.ImageIO.write(ImageIO.java:1520)
at com.ucab.javachat.Servidor.model.ServidorModel.run(ServidorModel.java:198)
The line ServiorModel.java:198 is: ImageIO.write(image, "jpg", new File(dir.getCanonicalPath()));
In my tests i can send images of 20, 30, 80, 200 Kb, but when i try to send the 2.1mb file gives the error.
I think this i related with some data loose on the byteArray (maybe header data?) but what i dont know is how to fix it, my register window method uses the same sockets and OutputStream to send data and i succesfully send a 24mb image.
As per the documentation:
Returns a BufferedImage as the result of decoding a supplied File with
an ImageReader chosen automatically from among those currently
registered. The File is wrapped in an ImageInputStream. If no
registered ImageReader claims to be able to read the resulting stream,
null is returned. The current cache settings from getUseCacheand
getCacheDirectory will be used to control caching in the
ImageInputStream that is created.
Note that there is no read method that takes a filename as a String;
use this method instead after creating a File from the filename.
This method does not attempt to locate ImageReaders that can read
directly from a File; that may be accomplished using IIORegistry and
ImageReaderSpi.
Make sure you register an ImageReader or wrap your file on a FileInputStream, but since your implementation works I bet it's the image causing issues therefore,
Make sure that your image is of type: GIF, PNG, JPEG, BMP, and WBMP for these are the types supported by the class.

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);

Image resizing using imgscalr API in 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.

Retrieve an image from the web in java

I am trying to read an image that resides somewhere on the web from my Java program. So far I have successfully loaded an image by using the following code.
URL url = new URL("http://www.google.com/images/nav_logo4.png");
Image img = Toolkit.getDefaultToolkit().getImage(url);
What I want to know is why this code (which is the first i tried) does not work:
BufferedImage img = ImageIO.read(new File("http://www.google.com/images/nav_logo4.png"));
This would have the benefit of giving me a BufferedImage. Also, how can I make the above code block until the image is loaded? I know I can use an ImageObserver, but is there a simpler way?
When I try the second option, I get this exception:
javax.imageio.IIOException: Can't read input file!
A File cannot refer to a URL.
Although I haven't tried it, there appears to be a ImageIO.read(URL) method, which can take an URL as the input as an URL object.
I would presume it would be called as follows:
ImageIO.read(new URL("http://url/to/my/image.png"));
File objects cant read from URLs

Categories

Resources