Convert String which is URL of image to byte array - java

I have an image content coming from Spring RestTemplate get result:
String url = "https://is2-ssl.mzstatic.com/image/" +
"thumb/Purple114/v4/15/a1/68/15a1681f-dec4-b01f-4362" +
"-e9ff1ece9c09/AppIcon-1x_U007emarketing-0-10-0-0-85" +
"-220-0.png/60x60bb.png";
String imageAsString = restTemplate.getForObject(url, String.class);
I know this is not a right way to fetch image by RestTemplate. But I should keep it for my old code.
How can I convert this value to right image byte array format?
imageAsString.getBytes() -> this is not the same with restTemplate.getForObject(url, byte[].class);

If you have an image URL, you can first read it into a BufferedImage and then write it to a FileOutputStream as follows:
public static void main(String[] args) throws IOException {
URL url = new URL("https://is2-ssl.mzstatic.com/image/" +
"thumb/Purple114/v4/15/a1/68/15a1681f-dec4-b01f-4362" +
"-e9ff1ece9c09/AppIcon-1x_U007emarketing-0-10-0-0-85" +
"-220-0.png/60x60bb.png");
BufferedImage bufferedImage = ImageIO.read(url);
ImageIO.write(bufferedImage, "png",
new FileOutputStream("resources/bufferedImage.png"));
}
Here is the image: bufferedImage.png

Related

Create image file from raw string data

for example, i have String like this:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHQAAAB0CAYAAABUmhYnAAAEd0lEQVR4Xu2c0ZLjIAwEk///6GzVvZlspWtWksNRnVcwiGmNwHaS5+v1ej38HKPAU6DHsPy3EIGexVOgh/EUqEBPU+Cw9biHCvQwBQ5bjg4V6GEKHLYcHSrQwxQ4bDk6VKCHKXDYcnSoQA9T4LDllB36fD5vlWR9fUvz0+ve9fp0/O7FU7w0n0CXhBSoDiXTRO06FBKKBLLkLvlGgkTp+UvndPzu/ul46Xq7x2/fQ8kR0wtOBaL+1J6uZ+3fPb5Aw0PRtxOWEkigAr3mCJUMuk9cM45uG3ZvJwel8dN4byW8+r1cgWYPVgRaLIlpwqWCT1cgHbr8skOgYUqkgtHwVYfQKZTiTW8rdCgQFWjtt2Pjty3TGdztOB0aHlosuVcHpglJ+h3nUFow7bE6dDOHCjRN2fBty917qEAF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3eX6CbA0rDE2iq2Ob9Bbo5oDS8H8eCMw7yCzx+AAAAAElFTkSuQmCC
i want to convert it back to an image file. here's what i've tried:
public void dumpFromRawData(String rawData, String wheretoPut) throws Exception{
byte[] imageByte = rawData.getBytes();
BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imageByte));
File file = new File(wheretoPut);
ImageIO.write(bufferedImage, "png", file);
}
where rawData is the example string above, and wheretoPut is the new image directory.. for example D:\\image.png
but when i run it, it gives me this:
Exception in thread "main" java.lang.IllegalArgumentException: image == null!
at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
at javax.imageio.ImageIO.getWriter(ImageIO.java:1592)
at javax.imageio.ImageIO.write(ImageIO.java:1520)
how could i resolve this? or is this not the correct way to convert it back to image?
The data of your image seems to be base64 encoded so you can not just convert this string into a byte array.
So you should use something like:
byte[] imageByte = Base64.decode(rawData, Base64.DEFAULT);
i finally found the solution. Thans #Chris623 for enlightening me :D
first, i need to separate the 'header' of the string file.. the data:image/png;base64, string, and then decode it to byte[]
String separator = ",";
String encoded = rawData.split(separator)[1];
byte[] decodedByte = Base64.getDecoder().decode(encoded.getBytes(StandardCharsets.UTF_8));
and then the rest of process is still the same.. the full method looks like this:
public void dumpFromRawData(String rawData, String wheretoPut, String fileName) throws Exception{
String separator = ",";
if(rawData.contains(separator)) {
// use this when the decoded string contains "," separator, like data:image/png;base64,
String encoded = rawData.split(separator)[1];
byte[] decodedByte = Base64.getDecoder().decode(encoded.getBytes(StandardCharsets.UTF_8));
// you can use this
// Path destinationFile = Paths.get(wheretoPut, fileName);
// Files.write(destinationFile, decodedByte);
// or this
BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(decodedByte));
File file = new File(wheretoPut+fileName);
ImageIO.write(bufferedImage, "png", file);
System.out.println("File has been Written as " + wheretoPut + fileName);
} else {
System.out.println("i haven't think about it yet.");
}
}

Cropping an image from URL to InputStream

I need to crop an image from the web (via its url) and return an InputStream (which can be uploaded to AWS S3). I am using org.imgscalr as the library and have the following method:
public InputStream cropFile(String url) throws Exception, IOException {
BufferedImage original = ImageIO.read(new URL(url));
BufferedImage target = null;
// resize based on http://www.htmlgoodies.com/beyond/java/create-high-quality-thumbnails-using-the-imgscalr-library.html
target = Scalr.crop(original, 410, 60, 200, 300, Scalr.OP_ANTIALIAS);
InputStream is = (InputStream) ImageIO.createImageInputStream(target);
Assert.assertNotNull(is);// it always returns null!!!
return is;
}
I call the method with something like:
InputStream is = cropFile("http://fengyuanchen.github.io/cropperjs/img/picture.jpg");
and then try to upload it to AWS S3:
PutObjectRequest request = new PutObjectRequest(AWSConfig.getBucket(), key, is, meta);
s3.putObject(request);
Unfortunately, I keep getting a null input stream (at the assert point above). If I change the createImage to:
ImageIO.write(target, "jpg", new File("c:\\dest.jpg"));
Then a proper image is written (so it works).

FileNotFoundException when reading a BufferedImage

I'm trying to crop an image received from a form upload. Before I crop it I save it, then I retrieve it again as a BufferedImage (because I don't know how to turn a part into a buffered Image). I then crop this image, but when I try to save it again I get a java.io.FileNotFoundException (access denied)
The first image gets saved correctly, I get the exception when I try to pull it back.
Is it possible to turn my part into a buffered image and then save it? Instead of doing double work. or else is there some fix to my below code.
String savePath = "path";
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
for (Part part : request.getParts()) {
//functionality to ormit non images
String fileName = extractFileName(part);
part.write(savePath + "/" + fileName);
String imagePath = savePath + "/" + fileName;
BufferedImage img = null;
try {
img = ImageIO.read(new File(imagePath));
img = img.getSubimage(0, 0, 55, 55);
ImageIO.write(img, "jpg", fileSaveDir);
} catch (IOException e) {
System.out.println(e);
}
}
ImageIO.write((RenderedImage im, String formatName, File output));
Parameters:
im a RenderedImage to be written.
formatName a String containg the informal name of the format.
output a File to be written to.
As per documentation output file parameter is the file object where it would be image written where you have passed the parent directory file object.

Getting Path of File Inside Jar

I'm trying to access an image located inside of a running jar.
Here is my code:
Image image = Toolkit.getDefaultToolkit().getImage(
getClass().getResource("/res/sprites/"));
The code above works absolutely fine.
The problem I'm having is a is converting it into a readable String to be used by a BufferedImage objet.
Here is my code: (pathRelativeToThis is a String)
Image path = Toolkit.getDefaultToolkit().getImage(
getClass().getResource("/res/sprites/" + pathRelativeToThis));
String image = "file://" + path.toString();
URL url = new URL(image);
BufferedImage img = ImageIO.read(url);
This doesn't work and gives javax.imageio.IIOException: Can't get input stream from URL! as an error.
What is the correct way to do this?
You can do it like this and work with stream directly:
InputStream is = getClass().getResourceAsStream("/res/sprites/" + pathRelativeToThis);
BufferedImage img = ImageIO.read(is);
is.close();
Also have you tried to pass resource URL to ImageIO directly?
URL url = getClass().getResource("/res/sprites/" + pathRelativeToThis)
BufferedImage img = ImageIO.read(url);
Remove path and just try to do this
String image = "file://" + getClass().getResource("/res/sprites/" + pathRelativeToThis);
URL url = new URL(image);
BufferedImage img = ImageIO.read(url);

Pass an Image from Flex to Java: BufferedImage == null

I want to pass an image (screenshot of a graph) from Flex to Java over BlazeDS. The goal is that the image will be stored on the serverside.
This is my Flex routine (called after clicking a button):
protected function btn_clickHandler(event:MouseEvent):void
{
var snapshot:ImageSnapshot = ImageSnapshot.captureImage(graphViewStack.selectedChild,);
var balanceSheetImage:String = ImageSnapshot.encodeImageAsBase64(snapshot);
//Testing the image
var base64Dec:Base64Decoder = new Base64Decoder();
base64Dec.decode(balanceSheetImage);
generatedImage.load(base64Dec.toByteArray());
}
In the 'generatedImage', the image is shown, so I assume this routine works.
Now I want to decode the balanceSheetImage in Java. For this reason, I created following Java code. The value contains the string in the generatedImage, which I copy/pasted from the flex code.
import sun.misc.BASE64Decoder;
public static int createPdf() throws IOException{
String value= "t3j1fA31VBp0DAADAJfR3rOfp+4+0H/qO+b//89/6u23566+//mVmZmZmZmb2yl4N8dSFcAzj0t29Xp//x77HfCvc/f8yAAAAfEL8FPT5wdm6/OBrf9SnsgtzAAAA+CBhDgAAAMIcAAAAhLkwBwAAAGEOAAAAwlyYAwAAgDAHAAAAYQ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hzYQ4AAADCHAAAAIS5MAcAAABhDgAAAIcw31fbbsIcAAAAxkn3lQePhTkAAAAMkNtWb41lYQ4AAADbYZ7C790xBwAAgMFh/vId863w/ie2/jfMXp1rzFxj5hozc32Za8zOf42dIcw/9h5zf1HNNwNzjZm5xsz1Za4xM2H+t498Kru/qOabgbnGzFxj5voy15iZMN+Zv6jmm4G5xsxcY+b6MteYmTAX5uabgZlrzFxjZq4vc42ZMBfm/qKabwbmGjNzjZnry1xjZsJcmJtvBmauMXONmbm+zDVmwlyY+4tqvhmYa8zMNWauL3ONmQlzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADeqXoJ2Elp11dtj+Hd5nCNJS8HO8ptsNd/w75285Lw5n/XzxvXlw6AA0jhLyrscX3N3TcG4cSe15j/lrH390thzrsVMc6O/65P068bI/GxDoCDyeGbAoy43oQ5e/KPC/Zwa98nkzBnpzBf42j2cvDmf9f3P+lTdQAc/5sC7Cn5Bwc7Wn9MTzSxhxr+O+Ya493fG/tQ8n9g885/1/fXVNEBIMy5djSJckbwHmD2uKZqN9cYe4a664t3h/mzO+Y6AIQ5F7u2/L//jPpHrDBHNPGn/zfM90ze+e/6373HXAeAMOci+k+adaeJva8zP5mBMOdP/m+Y64s9/l2/9ansOgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOBY/geGctMTogR6kgAAAABJRU5ErkJggg==";
BASE64Decoder decoder = new BASE64Decoder();
byte[] imgBytes = decoder.decodeBuffer(value);
ByteArrayInputStream str = new ByteArrayInputStream(imgBytes);
BufferedImage bufImg = ImageIO.read(str);
File imgOutFile = new File("newLabel.png");
ImageIO.write(bufImg, "png", imgOutFile);
return -1;
}
Unfortunately, this does not work. In particular: BufferedImage is always null. Has anyone a clue why this happens?

Categories