Saving image, webview, android - android

I am using webview in android to display images (mainly using google ajax API), Now if I want to save an image into local storage, How do I do ? I have image url, which can be used for saving.

If you have the image url, this is dead easy. You just have to retrieve the bytes of the image. Here is a sample that should help you :
try {
URL url = new URL(yourImageUrl);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
This will return a byteArray that you can either store wherever you like, or reuse to create an image, by doing that :
Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

I know this is a quite old but this is valid too:
Bitmap image = BitmapFactory.decodeStream((InputStream) new URL("Http Where your Image is").getContent());
With the Bitmap filled up, just do this to save to storage (Thanks to https://stackoverflow.com/a/673014/1524183)
FileOutputStream out;
try {
out = new FileOutputStream(filename);
image.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
out.close();
} catch(Throwable ignore) {}
}
IHMO much more cleaner and simpler than the accepted answer.

Related

How to save SVG in internal Storage And retrieve it and set it to ImageView?

I need to save the .svg in the Internal storage of android application and retrieve it and set it to the ImageView.
I am not able to save the .svg file. i am using this method -
File cacheDir = ctx.getCacheDir();
f = new File(cacheDir, name + ".png");
try {
InputStream in = new java.net.URL(imageurl).openStream();
mIcon = BitmapFactory.decodeStream(in);
try {
FileOutputStream out = new FileOutputStream(
f);
mIcon.compress(
Bitmap.CompressFormat.JPEG,
100, out);
out.flush();
out.close();
return f;
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
} catch (Exception e) {
return null;
}
Why are you decoding SVG into bitmap ? I'm not sure it is possible.
But if you want to save the SVG file to storage, just copy you input stream to the output stream.
Simple java solution :
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
or with IOUtils
If you want to display your SVG file, look at https://github.com/pents90/svg-android/tree/master/svgandroid

Extracting numbers from the captured image in android

I am doing an android app which involves a concept where I have to extract numbers from the captured image. Can you please help me or guide me a link where I could find the appropriate tutorials?
You have a good tutorial here where is explains method to create, to reading and writting files, in your case needs to read.
When you read this tutorial try my code that return a string of bytes:
public String formatPhoto_JPEGtoByteArray (String uri){
// Read bitmap from file
Bitmap bitmap = null;
InputStream stream = null;
ByteArrayOutputStream byteStream = null;
try {
stream = new BufferedInputStream(new FileInputStream(new File(uri)));
bitmap = BitmapFactory.decodeStream(stream);
byteStream = new ByteArrayOutputStream();
Matrix matrix = new Matrix();
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteStream);
// Convert ByteArrayOutputStream to byte array. Close stream.
byte[] byteArray = byteStream.toByteArray();
Log.e("-- FilesAndFolders.formatPhoto_JPEGtoByteArray --", "Last file of size: " + byteArray.length);
String imageEncoded = Base64.encodeToString(byteArray, Base64.NO_WRAP);
byteStream.close();
byteStream = null;
return imageEncoded;
}
catch (IOException ex) {
Log.e("-- FilesAndFolders.formatPhoto --", "Exception with " + uri,ex);
return null;
}
catch (Exception ex){
Log.e("-- FilesAndFolders.formatPhoto --", "Exception with " + uri,ex);
return null;
}
finally {
try {
if (stream != null) stream.close();
if (byteStream != null) byteStream.close();
} catch (Exception e) {}
}
}
Tell me if I helped you and good programming!

video record with camera intent to byte[]

I have a camera record intent, when the result is ok, i try to convert this video to byte[] to send a webservice:
Im doing this:
if (resultCode == RESULT_OK) {
// Video guardado
videoUri = data.getData();
if (videoUri != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileInputStream fichero_codificar = null;
try {
fichero_codificar = new FileInputStream(
videoUri.getPath());
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fichero_codificar.read(buf))) {
out.write(buf, 0, n);
}
byte[] videoByte = out.toByteArray();
strBase64 = Base64.encode(videoByte);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But in fichero_codificar = new FileInputStream(
videoUri.getPath())
logcat say me the file is not exists or the patch isnt propertly.
Anyone have a example for my qustion please?
thanks
Looks like you're finding the information incorrectly. Here is how I used the Camera intent in my application:
thumbnail = (Bitmap) data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(getPicName(index));
thumbnail.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
So maybe try something along those lines with a Video object rather than a Bitmap object. If that doesn't work, you could try .getAbsolutePath() instead.
Yeah it's definitely not doing what you think it does. I ran the debugger on mine and getPath returned this: /external/images/media/21 , which is a content Uri.

Android, Data Output Stream, Out of memory

I am using this segment of copy a large file. Android crashes with "out of memory" at exactly 32 buffer loads. It is acting like dos.write is putting the data into a large buffer rather than spooling it out to the i/o device. No exception is thrown.
The bufferSize = 512*1024. bis is a BufferedInputStream. byteArray is a ByteArrayBuffer,
try {
FileOutputStream fos = new FileOutputStream(file);
dos = new DataOutputStream(fos);
int current = 0;
while((current = bis.read()) != -1){
byteArray.append((byte)current);
if (byteArray.isFull()){
byte[] b = byteArray.toByteArray();
dos.write(b, 0, bufferSize);
byteArray.clear();
}
}
int count = byteArray.length();
byte[] b = byteArray.toByteArray();
dos.write(b, 0, count);
dos.flush();
dos.close();
bis.close();
}
catch (Exception e) {
RunTimeError("Exception: " + e);
return false;
}
My guess is that byteArray.isFull() is always returning false for some reason. Then when you have loaded 16MB of data, you're out of memory. I wouldn't bother with a ByteArrayBuffer. (For that matter, 512KB is way too large a buffer for this kind of operation. You should try to match the file I/O block size. It probably varies by device, but 4K-8K is probably close.) You also don't need to wrap fos in a DataOutputStream; you're just writing bytes. A BufferedOutputStream, on the other hand, might be useful. And if bis is not buffered, wrapping it in a BufferedInputStream will also help.
I would rewrite your code like this:
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(file), 8192);
byte[] buffer = new byte[1024];
int len = 0;
while((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
} catch (Exception e) {
RunTimeError("Exception: " + e);
return false;
} finally {
try { bis.close(); } catch (Exception ignored) { }
try { bos.close(); } catch (Exception ignored) { }
}

Trouble writing and reading image from/to internal memory on Android tablet (3.1)

I thought this wouldn't be too hard but have been banging my head against a desk for the last few hours and would really appreciate some help. Essentially, I want to get an image from a url, save it to internal memory (not sd card) and be able to retrieve that image and show it using an ImageView at a later time.
This is how I get the pictures from a url and write them to memory(urls are stored in "pics"):
String urlstring = pics[l][w];
if (urlstring != null){
try {
URL url = new URL(urlstring);
InputStream input = url.openStream();
FileOutputStream output = openFileOutput(("specimage"+l) + ("" +w+".jpg"), MODE_PRIVATE);
byte[] buffer = new byte[input.available()];
int n = input.read(buffer, 0, buffer.length);
while (n >= 0) {
output.write(buffer, 0, buffer.length);
n = input.read(buffer, 0, buffer.length);
}
output.close();
input.close();
} catch (Exception e) {
GlobalState.popupMessage(homePage, "Error", "Files could not be stored on disk");
}
}
This is how I attempt to retrieve them (path is the filename):
private Bitmap getPic(String path){
FileInputStream in;
Bitmap bMap = null;
BufferedInputStream buf;
try {
in = openFileInput(path);
buf = new BufferedInputStream(in);
byte[] bMapArray= new byte[buf.available()];
buf.read(bMapArray);
bMap = BitmapFactory.decodeStream(buf);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
System.out.println("excep.");
}
if (bMap == null) System.out.println("null");
return bMap;
}
If I do this the picture does not show up, but the program does not crash. An exception is not triggered. However, the value of bMap is given as null. I also get this strange message in the log:
DEBUG/skia(19358): --- SkImageDecoder::Factory returned null
Please let me know what I'm doing wrong. I have been ransacking my brain to no avail.
I should mention I do setImageBitmap in the ui thread.
Just try this, (Replace with your) and let me know what happen,
ImageView img = (ImageView)findViewById(R.id.imgView1);
FileInputStream in;
Bitmap bMap = null;
BufferedInputStream buf;
try {
in = openFileInput("icon.png");
buf = new BufferedInputStream(in);
byte[] bMapArray= new byte[buf.available()];
buf.read(bMapArray);
bMap = BitmapFactory.decodeByteArray(bMapArray,0,bMapArray.length);
img.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
System.out.println("excep.");
}

Categories

Resources