I am fetching image data from a hive which is stored as binary data like
by using an InputStream object. The problem is when I am trying to encode the image, it's getting encoded but again when I am trying to decode the same encoded image it's throwing an error.
My program looks like this:
File file=new File("path");
java.io.InputStream in = rs1.getBinaryStream("entity_image");
OutputStream f = new FileOutputStream(file);
int c=0;
while((c=in.read())>-1)
{
//System.out.println(c);
f.write(c);
}
byte[] imageBytes = new byte[(int)file.length()];
in.read(imageBytes, 0, imageBytes.length);
in.close();
String imageStr = encodeImage(imageBytes);//method that returns the encoded base64 String.
byte[] imageByteArray = decodeImage(imgstring);//method returning byte []
f.write(imageByteArray);//writing the decoded image to the file
The new image file is saying that it contains error while opening?
Are there any other ways available for fetching the image data from the hive?
I checked with getbytes() method, but it says the method is not supported.
Related
I am uploading a jpg to a spring controller endpoint. The image is uploaded as Base64 image/jpg which comes in as a MultipartFile. I am decoding the inputstream using Base64Decoder which seems to decode it ok but when I turn it into an InputStream to write it out to disk I can see it's been modified (according to what I can see in the debugger). When I save the file and open it it says it's an unsupported file type.
I took the multipart inputstream and wrote it directly to disk and I see the base64 encoding in notepad.
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4QBgRXhpZgAASUkqAAgAAAACADEBAgAHAAAAJgAAAGmHBAABAAAALgAAAAAAAABHb29nbGUAAAMAAJAHAAQAAAAwMjIwAqAEAAEAAAAACAAAA6AEAAEAAAAABgAAAAAAAP/bAIQAAwICCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCggKCgoKCgoICAgKCgoICAgICgoICAgKCgoICA0NCggNCAgKCAEDBAQGBQYIBgYICA0ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI/8AAEQgGAAgAAwEiAAIRAQMRAf/EAB0AAAIDAQEBAQEAAAAAAAAAAAMEAgUGAQAHCAn/xABJEAABAwIDBgQFBAIBAwMCAA8BAAIRAyEEMUEFElFhcfAGgZGhEyKxwdEHMuHxFEJSFSNiCDNyFoKSFyRDU6LCCTRjRHOy0uL/xAAbAQEBAQEBAQEBAAAAAAAAAAAAAQIDBAUGB//EACoRAQEBAQACAwADAAEEAwEBAQABEQIDcRIhMQQTsVEUIjJBBWGBwUIj/9oADAMBAAIRAxEAPwCgrFsRw4ZfWEs2FXUN4C7p4c10702ML4/M+p6jhzfqep/i4p0uS9Vtw8vddwRkX7t+ck1TdElWusVNVsRY3K1ngx2YFsz5rMYytJHX+7rSeDWGf6XHqf8A0938eZ02zK8LlWoMzwP9LwCV2jxC81j7kswTAYsE2Xto1OAzVPslvzHT8K8LV
Here's my controller and my code:
#PostMapping(value = "/saveBlueprintOrder")
public ResponseEntity<?> saveBlueprintOrder(#RequestParam MultipartFile blueprint,
#RequestParam(required = false) MultipartFile coversheet,
#RequestParam(required = false) MultipartFile logo,
#ModelAttribute BlueprintOrder blueprintOrder) {
if(coversheet != null) {
BASE64Decoder decoder1 = new BASE64Decoder();
byte[] imageBytes = decoder1.decodeBuffer(coversheet.getInputStream());
InputStream bis = new ByteArrayInputStream(imageBytes);
BufferedImage image = ImageIO.read(bis);
ImageIO.write(image, "jpg", new File("C:\\Users\\i58287\\Downloads\\coversheet.jpg"));
OutputStream stream = new FileOutputStream("C:\\Users\\i58287\\Downloads\\coversheet-test.jpg");
stream.write(imageBytes);
stream.close();
I just need to be able to translate this image to an inputstream so I can check the image locally in addition I need to send it to another api as such. What am I missing that's causing this image to be un-openable? Thanks for any help!
PS: I've done a lot of combinations so this is showing a couple options I have tried, BufferedImage image = ImageIO.read(bis) keeps returning a null image.
Ok so I don't know WHY this is what I had to do but I ended up saving my byte[] as a String and cut off the pre-pended
data:image/jpeg;base64
Then I decoded it into an InputStream. Anyone know why I had to do this?
Here's the code:
String imageBytes = new String(coversheet.getBytes(), StandardCharsets.UTF_8);
String imageDataBytes = imageBytes.substring(imageBytes.indexOf(",") + 1);
InputStream stream = new ByteArrayInputStream(Base64.getDecoder().decode(imageDataBytes.getBytes()));
BufferedImage image = ImageIO.read(stream);
ImageIO.write(image, "jpg", new File("C:\\Users\\i58287\\Downloads\\coversheet-test.jpg"));
When i make upload of a image in Android to the server (C #) it generates an error converting the image to byte Array, this happens with some images which is very strange because this error is not always generated, that is, depending the image is correctly converted or not.
The conversion code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 50, stream);
final byte[] img_byte = stream.toByteArray();
final String imageString = Base64.encodeToString(img_byte, Base64.DEFAULT);
When receiving in C# I make the following conversion in the string, generating a byte Array and then for the MemoryStream.
byte[] novaFoto = Convert.FromBase64String(NovaFoto.FotoString);
using (MemoryStream stream = new MemoryStream(novaFoto))
{
Image image = Image.FromStream(stream);
}
depending at the image the error appears in either Convert.FromBase64String or Image.FromStream.
Can anyone help me with this? If you have another method i like this.Thanks!!
I am using below code to convert base64 data to png image using java code but it always results in empty image. If i use the same base64 data to image in online services it works fine, below is the code, is there any issue with this code?
byte[] data = Base64.decodeBase64(imageInBase64);
System.out.println("Writing steam... " + data);
try (OutputStream stream = new FileOutputStream(new File("c:\\test.png"))) {
stream.write(data);
}
System.out.println("Converted..");
I'm trying to get the url of a range of images like that:
for(Element img : document.select(".left-column .strillo-content .lazy img[src]")) {
InputStream input = new java.net.URL(imageMainUrl).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
images.add(bitmap);
}
but everytime I trying to run my app I get this warning:
java.net.MalformedURLException: Unknown protocol: data
at java.net.URL.<init>(URL.java:184)
at java.net.URL.<init>(URL.java:127)
so I have tried to print the URL and I get this:
data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7
and I can figure out why, because I'm 100% sure that the element I select is corrent and also I do the same process with other section of the website and it works..
UPDATE 1:
I have tried this method to decode the ´base64´ image:
byte[] decodedString = Base64.decode(imageMainUrl, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
but the result is the same..
It's the data URI scheme
http://en.wikipedia.org/wiki/Data_URI_scheme
It allows to add inline data in your URI.
Extract the base64 part of the URI and get a byte array with parseBase64Binary, more information here : http://docs.oracle.com/javase/7/docs/api/javax/xml/bind/DatatypeConverter.html#parseBase64Binary%28java.lang.String%29
Use this array to build a ByteArrayInputStream
Use your BitmapFactory to decode it into a Bitmap
edit
This code works, it give a 1px*1px gif image. I used org.apache.commons.codec.binary.Base64 from commons-codec
String uri = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
byte[] decodedString = Base64.decodeBase64(uri.substring(uri.indexOf("data:image/gif;base64,") + "data:image/gif;base64,".length()));
ByteArrayInputStream is = new ByteArrayInputStream(decodedString);
FileOutputStream os = new FileOutputStream(new File("/tmp/test.gif"));
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
is.close();
os.close();
I have an issue about my Application in detail.
- I have a java servlet receive data from mms gateway (MM7 protocol)
I get inputstream (image content , message content ) convert to string
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//String orgin = new String(byteArrayOutputStream.toByteArray(),"UTF-8");
String orgin = Streams.asString(request.getInputStream(), "ISO-8859-1");
Then I substring orgin for image content and convert to base64 and save to image file
but string that I convert to base64 can not save to image because this error
not a jpeg file
I print out string base64 does not start with /9j that mean not jpg format
please suggest or give an example for me
Best reqard
lieang noob noob
sorry for my english :)
This is at least part of your problem:
String orgin = Streams.asString(request.getInputStream(), "ISO-8859-1");
You shouldn't be converting it into a string to start with. It's binary data, right? So read it from the stream as binary data.
Now it sounds like you basically want to get separate "chunks" of that binary data - but converting the data into a string format to start with is not appropriate, unless that binary data really is encoded text.
I think, this might help: http://www.dailycoding.com/Posts/convert_image_to_base64_string_and_base64_string_to_image.aspx
Encoding of image is very simple.
Encoding Source:
Bitmap bm = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] byteArray = baos.toByteArray();
encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Decoding Source:
byte[] decodedString;
decodedString = Base64.decode(picture, Base64.DEFAULT);
imageView1.setImageBitmap( BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length));
Use the below code the for the String to Image
here "origin" is a String
import org.apache.commons.codec.binary.Base64;
byte[] imgByteArray = Base64.decodeBase64(origin);
FileOutputStream imgOutFile = new FileOutputStream("C:\\Workspaces\\String_To_Image.jpg");
imgOutFile.write(imgByteArray);
imgOutFile.close();