Is base64encode and decode in dart is same for Java. In my flutter app I want to upload an image. I convert that image to string by base64Encode(file. readAsBytesSync()). And then I passed it to backend. Backendcode is in JAVA. I want to decode this image file in java for save into a folder. How it is possible. Is I decode image gives same result.? I want to fetch it back also. Please help
Putting all my comments as an answer here are 2 utility functions
public static BufferedImage decode(String base64Image)throws Exception
{
Base64.Decoder decoder=Base64.getDecoder();
ByteArrayInputStream decoded=new ByteArrayInputStream(decoder.decode(base64Image));
return ImageIO.read(decoded);
}
public static void writeImage(ByfferedImage img,File file)throws Exception
{
ImageIO.write(img,"png",file);
}
Related
I'm working on a .opus music library software which converts audio/video files to .opus files and tags them with metadata automatically.
Previous versions of the program have saved the album art as binary data apparently as revealed by exiftool.
The thing is that when I run the command to output data as binary using the -b option, the entire thing is in binary seemingly. I'm not sure how to get the program to parse it. I was kind of expecting an entry like Picture : 11010010101101101011....
The output looks similar to this though:
How can I parse the picture data so I can reconstruct the image for newer versions of the program? (I'm using Java8_171 on Kubuntu 18.04)
It looks like you're trying to open the raw bytes in a text editor, which will of course give you gobble-dee-gook since those raw bytes do not represent characters that can be displayed by any text editor. I can see from your output from exiftool that you are able to know the length of the image in bytes. Providing you know the beginning byte position in the file, this should make your task relatively easy with a little bit of Java code. If you can get the starting position of the image inside your file, you should be able to do something like:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class SaveImage {
public static void main(String[] args) throws IOException {
byte[] imageBytes;
try (RandomAccessFile binaryReader =
new RandomAccessFile("your-file.xxx", "r")) {
int dataLength = 0; // Assign this the byte length shown in your
// post instead of zero
int startPos = 0; // I assume you can find this somehow.
// If it's not at the beginning
// change it accordingly.
imageBytes = new byte[dataLength];
binaryReader.read(imageBytes, startPos, dataLength);
}
try (InputStream in = new ByteArrayInputStream(imageBytes)) {
BufferedImage bImageFromConvert = ImageIO.read(in);
ImageIO.write(bImageFromConvert,
"jpg", // or whatever file format is appropriate
new File("/path/to/your/file.jpg"));
}
}
}
I have the following method to load resources as String where path is the String to the resource on my classpath (which works just fine on plain text):
try (Scanner scanner = new Scanner(MyClass.class.getResourceAsStream(path))) {
return scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
}
Now I want to load a PNG image as a base64 String so I can send it back through sparkjava with Content-Type: image/png.
How can I do that?
Do not use any libraries, only plain old Java.
After setting the MIME type in the header with response.header("Content-Type", "image/png") (look up your MIME type here), you can use this:
try {
return Files.readAllBytes(Paths.get(MyClass.class.getResource(path).toURI()));
} catch (IOException | URISyntaxException exception) {
exception.printStackTrace();
}
return null;
Apart from that, to base64-encode a String in Java 8, you can use the java.util.Base64.Encoder class, so you'd just run the result of the method I posted in my description through
Base64.getMimeEncoder().encodeToString(resourceAsString.getBytes(StandardCharsets.UTF_8))
and send it back as response. I haven't got it to work for me though, for some odd reason. I simply used my framework's static files feature.
I am trying to convert TIF / TIFF images to JPG which works fine but for few TIF images I am getting an IllegalArgumentException: Bad endianness tag (not 0x4949 or 0x4d4d).
Exception :
java.io.IOException: Bad endianness tag (not 0x4949 or 0x4d4d).
at com.sun.media.jai.codecimpl.CodecUtils.toIOException(CodecUtils.java:76)
at com.sun.media.jai.codecimpl.TIFFImageDecoder.getNumPages(TIFFImageDecoder.java:98)
at com.sun.media.jai.codecimpl.TIFFImageDecoder.decodeAsRenderedImage(TIFFImageDecoder.java:103)
at com.sun.media.jai.codec.ImageDecoderImpl.decodeAsRenderedImage(ImageDecoderImpl.java:140)
at com.pkg.jae.utils.GenericImageUtils.convertTiffToJpg(GenericImageUtils.java:35)
at com.pkg.jae.utils.GenericImageUtils.main(GenericImageUtils.java:92)
Caused by: java.lang.IllegalArgumentException: Bad endianness tag (not 0x4949 or 0x4d4d).
at com.sun.media.jai.codec.TIFFDirectory.getNumDirectories(TIFFDirectory.java:595)
at com.sun.media.jai.codecimpl.TIFFImageDecoder.getNumPages(TIFFImageDecoder.java:96)
... 4 more
Code Function :
public static void convertTiffToJpg(String strTiffUrl,String strJpgFileDestinationUrl) throws Exception {
try {
FileSeekableStream obj_FileSeekableStream = new FileSeekableStream(new File(strTiffUrl));
ImageDecoder obj_ImageDecoder = ImageCodec.createImageDecoder(EXT_TIFFX, obj_FileSeekableStream, null);
RenderedImage obj_RenderedImage = obj_ImageDecoder.decodeAsRenderedImage();
JAI.create("filestore", obj_RenderedImage,strJpgFileDestinationUrl, EXT_JEPGX);
obj_RenderedImage = null;
obj_ImageDecoder = null;
obj_FileSeekableStream.close();
} catch (Exception ex) {
throw ex;
}
}
If anyone knows the issue and can help in this.
As stated in a comment by bitbank, this means you're passing a JPEG file to it when it expects to get a TIFF file.
Startlingly, this JAI
RenderedOp renderer = JAI.create("fileload", filename);
BufferedImage bi = renderer.getAsBufferedImage();
does not have the same failure and just works regardless of image "kind." Don't use this particular method (passing in the filename) though, see Is JAI closing file handles too early?
I had this issue and it turned out to be a front-end problem. Yes, I was trying to upload the wrong file type, but I was expecting correct handling and a gracious popup message alert. Instead I was getting the error you described.
In my case, I was using extjs and I had a failure function like this:
failure: function (a) {
...some message alert...
}
instead of:
failure: function (f, a) {
...some message alert...
}
and this was throwing that exception, instead of displaying my message alert.
I'm actually working on a GWT based website.
Now I'm stuck on how I should display images stored in a database on my website.
Basically I've a bytearray in my database, which I fetch using hibernate.
Now should I probably create an ... tag out of that data, but I don't know how
I'm using GWT in Java and Hibernate
Here is the solution. First you should encode the byte array by using com.google.gwt.user.server.Base64Utils.toBase64(byte[]) . But this method does not work for IE 7. and IE8 has 32kb limit.. IE9 does not have this limit.
here is the method on the server
public String getImageData(){
String base64 = Base64Utils.toBase64(imageByteArray);
base64 = "data:image/png;base64,"+base64;
return base64;
}
Here is the client method ;
#Override
public void onSuccess(String imageData) {
Image image = new Image(imageData);
RootPanel.get("image").add(image);
}
I don't know how GWT works, albeit you can map a servlet/controller which returns resourceStream.
For example if you map a servlet "imageViewer" which takes imageId param, request to image would become
/imageViewer?imageId=1234
Hibernate object would have reference to the blob, so you can return that.
Reference on UI would be
<img src="/imageViewer?imageId=1234"/>
Update: You may not be able to use Model as it is to return image, you would need an explicit controller or servlet which returns stream data.
In servlet you would do something like
// get reference to input stream
InputStream in = hibnerateObject.getImage();
// set MIME type etc
response.setContentType(mimeType);
OutputStream out = response.getOutputStream();
while ((len = in.read(buf)) >= 0)
out.write(buf, 0, len);
in.close();
out.close();
There is Image Widget in GWT. You can't do it client-side but you can call RPC to communicate with the server. Then it is simple CRUD application. In server connect to database with hibernate and return the Image to the client or it's url and on the client-side do something like that :
#Override
public void onSuccess(String imageUrl) {
Image image = new Image(imageUrl);
RootPanel.get("image").add(image);
}
#Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
That's all. Happy coding
I used the same approach as Gursel Koca suggested but could only get it to work using the Apache Base64 library, not (ironically) the GWT Base64Utils
String base64 = Base64.encodeBase64String(array);
base64 = "data:image/"+type+";base64," + base64;
return base64;
Also note that if you are updating an existing image or an image placeholder, the setURL method will overwrite your stylesheet, so make sure to grab that first:
String styleName = profilePicture.getStyleName();
profilePicture.setUrl(base64String);
profilePicture.setStyleName(styleName);
I am a .NET Developer, but the question I am having is not related to .NET
Please keep this in mind even if my question sounds very trivial.
This is my question:
We have an swf in the browser, which communicates with a java extension
Its done using Smartfox Server(Used for MMO apllications)
From the swf we are grabbing a portion of the screen as "Byte Array" in action script(3).
And in Java, we are calling a function that converts the ByteArray to Image and then saves it.
Our Java developer is encountering the error
java.lang.illegalArgumentException
when the java function executes.
So basically, what I would like to know is this:
How to accept the object type Byte Array from ActionScript in Java?
Whats Java object type that is mapped to Byte Array in ActionScript?
The conversion part is easy, I dare say.
Update:
The code in the ActionScript Section
public function savePhoto(uName:String, ba:ByteArray, descr:String):void{
var obj:Object = {};
obj.arr = ba;
obj.desc = descr;
sfsConnectobj.photoSectionSave(obj,"save");
}
public function photoSectionSave(targetObject:Object,type:String) {
sfs.sendXtMessage("trialjava", "save", targetObject);
}
The first function calls the SmartFox Extension in Java.
The extension name is "trialjava.js"
The Java Code that accepts the function is
public void handleRequest(String cmd, ActionscriptObject ao, User u, int fromRoom)
{
try {
ActionscriptObject arr = ao.getObj("arr");
String dirName="C:\\";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos;
oos = new ObjectOutputStream(bos);
oos.writeObject(ao.getObj("arr"));
oos.flush();
oos.close();
bos.close();
byte [] data = bos.toByteArray();
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(data));
ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Array reading not succesful. Error is: "+e);
}
}
Seems like there was a small mismatch in retrieving the objects by java.
Now the error is different.
Array reading not succesful. Error is:
java.io.NotSerializableException:
it.goto
andplay.smartfoxserver.lib.ActionscriptObject
Regards,
naveenj
flash.utils.ByteArray is mapped to Java's byte[] type.
I am not sure if this is an issue, but according to Flash security model, if SWF is loading media from any host/domain other that the one it was loaded, screen capture would result in error.
Can you check the byte array you received? What is its size? And try to print its starting few values.
Byte array is not received directly. It comes inside an AS object. The real question here is how to get this byte array inside the ActionScript object to a Java byte array object.
I am the aforesaid Java developer and I am doing this.