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();
Related
Well, i'm trying to send a picture from android to java, if i make it with compression it works really good, but i need to make it without compression beacuse i need a good or normal quality.
FixBitmap is my current Bitmap picture
//Android
FixBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.e(TAG,"LENGTH"+ConvertImage.length());
Length 43388
//Java
try{
String file=request.getParameter("image_data");
String filename=rt.getId()+"_"+rt.getName()+".png";
BufferedImage image = null;
byte[] imageByte;
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(file);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
File outputfile = new File(filename);
ImageIO.write(image, "png", outputfile);
Path destinationFile = Paths.get(getServletContext().getRealPath("/")+"uploads\\", filename);
Files.write(destinationFile,imageByte);
}catch(Exception ex){
System.out.println("Error :"+ex.getMessage());
}
This code actually works as i said, but the compression make it looks in a very bad quality, so i tried to make it without compression, just converting my bitmap to a byte array, just like this
ByteBuffer buffer = ByteBuffer.allocate(FixBitmap.getRowBytes() *
FixBitmap.getHeight());
FixBitmap.copyPixelsToBuffer(buffer);
byteArray = buffer.array();
ConvertImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.e(TAG,"LENGTH"+ConvertImage.length());
Length 252107
The code on my java side it's the same but now it doesn't work, it just shows me this error :
java.lang.IllegalArgumentException: image == null!
So I decided to print the length because maybe there is some restrictions about this...
so I hope you can help me with this (just send/get the picture without compression)
I am converting an image as a DLFileEntry from JPG to PNG format using the following code.
try {
DLFileEntry dlFileEntry = DLFileEntryServiceUtil.getFileEntry(dlFileEntryId);
InputStream inputStream = dlFileEntry.getContentStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] byteArray = buffer.toByteArray();
ImageBag imageBag = ImageToolUtil.read(byteArray);
RenderedImage renderedImage = imageBag.getRenderedImage();
if (renderedImage == null) {
throw new IOException("Unable to decode image");
}
renderedImage = ImageToolUtil.scale(renderedImage, 2000);
buffer = new ByteArrayOutputStream();
ImageIO.write(renderedImage, "png", buffer);
InputStream fis = new ByteArrayInputStream(buffer.toByteArray());
DLAppServiceUtil.updateFileEntry(
dlFileEntry.getFileEntryId(),
dlFileEntry.getName(),
MediaType.IMAGE_PNG_VALUE,
dlFileEntry.getTitle(),
dlFileEntry.getDescription(),
"",
true,
fis,
buffer.size(),
serviceContext);
} catch (Exception e) {
e.printStackTrace();
}
Even though it updates the image content type and extension in "Documents and Media", when we try downloading the image, it is still in JPG format.
The image looks like above in Documents and Media. You can see that the content type has become image/png.
Above shows the screenshot while I tried to Download this image and save it. It is still in the original format of JPG when I try downloading. What should I do in addition to the code above, inorder to completely convert the image to PNG?
You still store the old file name: dlFileEntry.getName()
I would guess that jpeg or jpg is the extension of the old file name and the browser determines his file filter from the extension.
So better exchange the extension as well:
DLAppServiceUtil.updateFileEntry(
dlFileEntry.getFileEntryId(),
dlFileEntry.getName().replaceAll("\\..*?$",".png"),
...
This will change the extension that is stored for that file
Hello I am working with android image processing via base 64 encoding and decoding.I need to send an encoded base 64 string to server as a string . When I tried it in android side , I can able to decode it into original image.and my decoding and encoding are as follows
public void base(Bitmap bitmap)
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
toimag(encoded);
String a=encoded.replaceAll("\\s+","");
Log.i("strrr",a);
}
public void toimag(String encodedImage)
{
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
logo.setImageBitmap(decodedByte);
}
But I cant able to get the actual image using http://www.askapache.com/online-tools/base64-image-converter/ . It show only a part of my actual image. This is my base 64 string
iVBORw0KGgoAAAANSUhEUgAAAyAAAAJYCAIAAAAVFBUnAAAAA3NCSV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KCdluwYunWUtBka9WIoTvm
8eGU7q81h6aku2V9vihyBFOdpUuctVF1PrLFcZ8pARqzE70NDUkIqBExNmPYWJSUK+6Iq6CYEqgZ
NdUAug0jmCZl4gscI6G28y5Y1zipy/FwWAoDf4jPVAr81WCM4rWbDX6FMJiQitGiaK6YAC4AKgyE
gvEvbZqIFrYHKhtbmwV9GkxNQwibe5Q1kVNCrPxz/GztFBNA1ZU0aAjHak2A6SZUBVVB0SDjhoRS
sAun5Cq2TxgWCSRNsrruzw7BwupQkmM7LZVbCK0wWzLw4dFGhYb56pRVwhCzjn3MSKO5BlWoUYTC
AkrgsZFamr40Em5ueLNwNMsYFMptlHZwHF9vVCFDRE8MiPBoqA+/LTiTEdkQcQvfobOz0wpdsdH3
zfgKBjmkWKeB4mQmQXypZw8gxbEaGgfHSf3g4beNTMx7fpliC+u/b+mFQ48BAx80YGiiZjNWfD8S
gU+ptQavW+iHNo9j9sdSp+fJaEHxoAMHoz2iK79SEYqcoXahaVxmc/02hyI2oYf2VgPsLkpa8LMb
WEIWhUMdCYayCGMk+7YsnBIdBjNQCj93yhtcu6OFYSJBvjKFyuEU9xAmFGGoHIT136zywFiDSrsB
wCab+wB1f6tESJuWKi2EWhOa3WrDgEfRQNI7VYuImI15OGaAmgpliNB1zCG3+LQaYwzYS5Vj3slo
p1JTdIpCIqTl9AcFBXQDVBxjDdQ8uPYxItf8QAHpfkJaSYEmHUqtp6Ah+hzxUYC6
How can I resolve this issue ? Is there any problem with this encoded string ? Please help. Thanks in advance :)
It appears you are cutting and pasting from the logcat. logcat truncates long messages, so you should not rely on it for copying large pieces of data. You should save the base64 string out to a file and then try your validation using that file.
For Encode image to Base64
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncode = Base64.encodeToString(b,
Base64.DEFAULT);
For decode image
byte[] decodedByte = Base64.decode(imageEncode, 0);
Bitmap newBitmap = BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
logo.setImageBitmap(newBitmap);
In my android App I download some photographs from the internet.How can I verify that an image from the web is correctly downloaded? I've thought of checking the file's size I've just written on sd is greater that zero, but I don't know if this is sufficient. this is my code
String filename =title.replace(" ","")+j+".nomedia";
File destination = new File(MyApplication.getPhotoStorage() ,filename);
URL url = new URL (url_image);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destination);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
localPhotosUrl.add(destination.getAbsolutePath());
The only possibility I can think of is comparing the files checksums. Thus the server would have to provide the checksums for the files it provides. Then youl would download the file and the checksum, generate the checksum for the downloaded file locally and then compare the downloaded checksum with the generated. The checksums can be generated for example with MD5 but there are other hashing algorithms, too.
Here is shown how you can generate the MD5 checksum for files in Java without much overhead: Getting a File's MD5 Checksum in Java
For your code it would be applied like this:
String filename =title.replace(" ","")+j+".nomedia";
File destination = new File(MyApplication.getPhotoStorage() ,filename);
URL url = new URL (url_image);
OutputStream os = new FileOutputStream(destination);
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream is = url.openStream()) {
DigestInputStream dis = new DigestInputStream(is, md);
byte[] b = new byte[2048];
int length;
while ((length = dis.read(b)) != -1) {
os.write(b, 0, length);
}
}
byte[] digest = md.digest();
os.close();
localPhotosUrl.add(destination.getAbsolutePath());
I guess the easiest way here would be to try to decode it with Bitmap.DecodeFile. If your bitmap can properly be loaded, then it has been downloaded successfully.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
int width = opts.outWidth;
int height = opts.outHeight;
We use options.inJustDecodeBounds so that as to keep memory usage low. We don't want a copy of the bitmap but just to check the decoder knows what to do with the file.
If width and height are greater than zero, your bitmap is not corrupted.
Obviously this only works because you are downloading photos and not some random files. If these can ben any kind of files then the md5 answer is a good one.
Unless the server also provides some sort of hash value alongside the files (SHA1, MD5, etc.), you can't really. You could try parsing the image file (create a Bitmap, etc.) object, but that could be too memory intensive if you are downloading a lot of files. Just keep it best effort :)
What is the efficient way to encode and decode an audio file in android
I have tried the Base64 as below but after decoding the file size get increased.
Encode
ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
File file = new File(path);
FileInputStream objFileIS;
try {
objFileIS = new FileInputStream(file);
byte[] byteBufferString = new byte[1024];
for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1;) {
objByteArrayOS.write(byteBufferString, 0, readNum);
System.out.println("read " + readNum + " bytes,");
byte[] bytes = FileUtils.readFileToByteArray(file);
strAttachmentCoded = Base64.encodeToString(bytes,
Base64.DEFAULT);
Decode
byte[] decoded = Base64.decode(strAttachmentCoded,
Base64.DEFAULT);
// byte[] decoded1 = Base64.decode(byteBinaryData1, 0);
File file1 = new File(pathAudio);
FileOutputStream os = new FileOutputStream(file1, true);
os.write(decoded);
os.close();
i want audio in String format to send to server and retrieve the same as per the user requirement.
wikipedia:base64 (rfc3548) is the right method to choose I would think. It is most common now I think having taken over from wikipedia:uuencoding.
To answer the question . . .
You could add some padding. The wikipedia article on base64 gives a good example of padding.
Or you could add a header to your audio string including length. The header could also include other control data so it may be something you want to include anyway.