1

Every answer I found on Internet needed to know the filename or the URL of the image in order to make conversion. I only have access to the image instance, I can't access it on the filesystem. I don't have its URL nor filename.

Typically, that's the kind of code I found but it's not relevant :

File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
Roman C
  • 49,761
  • 33
  • 66
  • 176
chd
  • 141
  • 3
  • 9
  • The "code that uses the file system" simply *loads* the image. That step can be skipped or replaced. Do that: Given an `java.awt.Image` (this kind?), what is needed next to obtain the "base 64"? What does the "base 64" require? What steps can be taken to get from one to the other? The answer will probably be in Streams and writing the file to a *memory stream*. – user2864740 Dec 30 '17 at 22:56
  • https://stackoverflow.com/a/17595742/2864740 – user2864740 Dec 30 '17 at 23:00
  • Yes, it's java.awt.Image. In order to obtain base64, I need first (I think) to obtain a bytearray of the image. – chd Dec 30 '17 at 23:00
  • Good - in that case, see the link above. That should be enough to get a good start! – user2864740 Dec 30 '17 at 23:02
  • OK, I'll have a look, thanks. – chd Dec 30 '17 at 23:06

2 Answers2

0

Once you have a BufferedImage, you can try this code. Then if you need to convert it to base64 there's a lot of utilities.

One of the image converter I found here. There should be a lot more such APIs.

I have found that I did the same by Base64Encoder in this answer.

Roman C
  • 49,761
  • 33
  • 66
  • 176
0

This should get you an idea on how to encode to base64, if you only have access to the image data. Let's say your image data is a byte array, then you can do this:

byte[] image = // your image data here;     
byte[] encodedImage = java.util.Base64.getEncoder().encode(image);

This is how to convert from image to byte array: https://stackoverflow.com/a/3211685/3302747

Baked Inhalf
  • 3,375
  • 1
  • 31
  • 45