How to write a Bitmap out to a XML file - android

Might sound crazy, but it's what I need to do. I want to take a Bitmap object and use the XMLPullParser/XmlSerializer to write this to a flat file. Obviously I will need to read the XML tag back into a Bitmap object.
I have tried various things, similar to how I write and read Bitmaps from a database.
Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
byte[] bitmapByte = outputStream.toByteArray();
Where I get lost is once I write this out to my XML file as a String, I can never get it converted back properly. Any pointers is appreciated.
Edit:
I want to provide a little more information. I am writing out a good deal of XML data for a backup purpose, so loading or writing time is of no concern. This is not a main source of the data (main source is a SQLite database). I do not want to have to write out a couple of very small (48x48pixel) images as well if I can help it.
I am reading in my XML using the XMLPullParser, which reads a String:
if (name.equalsIgnoreCase("someXmlTag")){
String someString = parser.nextText();
I am writing out my XML using the XmlSerializer, which writes a String:
XmlSerializer serializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
serializer.setOutput(writer);
serializer.startDocument("UTF-8", true);
serializer.startTag("", "someTag");
serializer.text(someString);
So somehow I have to turn my Bitmap into a String and then turn that String back into a Bitmap. I will do some searches on Base64 to see if I get any good examples.

I would suggest using something like Base64 encoding.

The XMLPullParser is, as its name suggests, a parser, it's not used to write XML. Your best bet is to store it as Base64 like mentioned before.
Needless to say, this is going to take a lot of space for no good reason.
It will also be a lot slower to read back.

Related

Android : Bitmap causing out of memory error

I have been going crazy with this android error and from browsing the previous posts about this error none of the solutions that were given helped me.
I am of course talking about the all powerful killer known as the 'android Out of memory on a (NUMBER)-byte allocation.' I am trying to create a photo uploader and after the 3rd maybe 4th image my app crashes. I know to stop the crash to use a catch exception however that is not my problem. I am here to ask the community is there any solution to fixing this byte allocation error ?
Here is a snippet of my code involving the bit map .
String post = editTextPost.getText().toString().trim();
// get the photo :
Bitmap image = ((BitmapDrawable)postImage.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// compress the image to jpg format :
image.compress(Bitmap.CompressFormat.JPEG, 45, byteArrayOutputStream);
byte[] imageBytes = byteArrayOutputStream.toByteArray();
String encodeImage = Base64.encodeToString(imageBytes,Base64.DEFAULT);
// Recycle bitmap :
image.recycle();
image=null;
// send data :
sendPost p = new sendPost(this);
p.execute(post, encodeImage);
imageBytes=null;
Im not using any libraries and would like to keep it that way however if using a library is the only option I will use one. Hopefully someone can help.
Bitmaps won't completely recycle if they are attached to a View, for example to a ImageView, if you do imageView.setImageBitmap(bitmap), you need to clear it before doing imageView.setImageBitmap(null) and clearing any other reference to any view.
After you finish uplloading the image release the memory occupied by the "postImage" -
postImage.setImageDrawable(null);
This will release any memory occupied by the bitmap associated with postImage
General Answer:
When you upload files you need to open a stream to your server and to
your file at same time. read and write chunk by chunk of 1 MB for
example. this way you will not get an out of memory exception.

Android - java.lang.NoSuchFieldError: android.graphics.Bitmap$CompressFormat.WEBP

I'm trying to use a very simple piece of code that has been supported since API 1.
if (bitmap != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.WEBP, IMAGE_QUALITY, byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
result = Base64.encodeToString(bytes, Base64.DEFAULT);
}
somehow,
bitmap.compress(Bitmap.CompressFormat.WEBP, IMAGE_QUALITY, byteArrayOutputStream);
gives me that weird error: java.lang.NoSuchFieldError: android.graphics.Bitmap$CompressFormat.WEBP and this only happens on my moto razr 2.3
i can't find anything on the internet about this. what's going on? (i get that, clearly, motorola's stock android didn't think to include it, but how would i fix this?) any hints?
all i want to do is to compress take a snapshot of the screen (or view), and attach it IN A USER FRIENDLY WAY in String form (this same device also doesn't do file attachments correctly either) to the body of an email intent, and pass that off to whoever can send emails.
trying to compress to .jpeg, then converting it to base64 encoded string, and then attaching to email in the body takes forever, and is not very user-responsive. this can't happen.
any help?
android.graphics.Bitmap$CompressFormat.WEBP only works for api level 14 or above.
Try some WebP libraries.
WebP library for java?

How can i use poi to read ppt?

i find it supports well in Java,i can convert it to jpg;
but when i use it in Android,bufferimage,graphics,imageio are not support
becuase android drop the java.awt
so if i want to use poi in android,how can i do
tell me something useful, thks.
swamy gave you rather useful link.
as of bufferedImage, you can adopt it and write your own adapter, as I did:
BufferedImage image = ImageIO.read(url);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( image, "jpeg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close();
int idx = ppt.addPicture(imageInByte, XSLFPictureData.PICTURE_TYPE_JPEG);
XSLFPictureShape pic = xslfSlide.createPicture(idx);
I got docx4j (which can handle pptx) running on Android; see jaxb-can-be-made-to-run-on-android
The reason I mention this, is I had to overcome java.awt issues, which might help you. I repackaged as https://github.com/plutext/ae-awt
If you want to use that with POI, you'd have to alter the references in POI.
If you are just using pptx, you might find it easier to use docx4j (since with POI, you'll probably also need to get XML Beans working on Android).

The image is too small when I try to upload it using Facebook Graph API and Android

Simply put I need to capture image using camera and upload it to facebook via my android application. And I successfully did that. The problem is when the photo posted in facebook, it's just too small and in low resolution while the image I took is in high resolution.
I understand that: in order to upload to facebook, i need to convert the captured image which is in bitmap format into byte array. So i have method for that:
public static byte[] convertBitmapToByteArray(Bitmap bm){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.PNG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
return bitmapdata;
}
Then to upload the image to facebook, i have code below where byteData is byte array I converted from bitmap image using the method above.
parameters.putString("message", "Test");
parameters.putByteArray("source", byteData);
String facebookResponse = facebookInstance.request(albumId+"/photos",parameters,"POST");
return facebookResponse;
I am pretty sure the problem is my convertBitmapToByteArray method since the method is to compress the bitmap image and turn it into byte array, and this made my image into low resolution image. However I can't seem to find the way to upload the image without converting it into byte array first. Any solution for me?
Alright even this thread is old, i found out the answer. It's not the problem of CompressFormant.JPEG or CompressFormat.JPG. Simply put, intent in android isn't designed to carry big data like image from activity through activity. I need to save the image from intent to sd card first before able to pull it out from there. It's my solution.

Can Bitmaps be written to cache using ObjectOutputStream?

I have a method called loadFromCache and it returns a bitmap if it is found in the cache. Long story short I have it narrowed down to this method, returning null at the end if the try/catch fails.
FileInputStream fis = new FileInputStream(getCacheDir()+(""+position));
ObjectInputStream ois = new ObjectInputStream(fis);
Bitmap temp = (Bitmap)ois.readObject();
fis.close();
return temp;
I have previously tried the Bitmap.compress(...) methods to save bitmaps but they were a little slow for my needs... Yes the bitmap has been written to these positions, but I don't know if it (Bitmap) is serializable so is it actually saving? And yes I remembered to flush when I wrote the file.
How is Bitmap.compress() too slow for you? The only faster(?) way would be to write the bitmap unchanged to disk, see below.
Using MappedByteBuffer together with Bitmap.copyPixelsToBuffer() may work. I haven't tested this but it seems like it could work. Note that you most likely will have to store image dimensions yourself.
Sharing an experience I just had with Bitmap.compress being very slow:
My source image was a jpeg, and I was passing Bitmap.CompressFormat.PNG to bitmap.compress. This caused the compress operation to take 10-15 seconds.
Once I changed it to JPEG (such that the source and destination file remain the same image format) then the operation takes less than a second. Perhaps the original question came about through a similar means, and maybe someone else finds this helpful.

Categories

Resources