Extracting numbers from the captured image in android - 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!

Related

Camera base64 image cannot be converted to Bitmap

I have been having trouble converting the base64 String Image that is being sent to me by the backend.
So this is how the backend sends the data.
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
And this is how we convert it.
final byte[] data = Base64.decode(base64, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(data, 0, data.length);
The result is always null. Any help is highly appreciated.
EDIT:
These are the back end codes.
#Override
public BufferedImage base64ToImage(String base64Image) throws IOException {
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));
return img;
}
public static String imgToBase64String(final RenderedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString();
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
And this is our converting tool before sending the Base64 Image String to the back end.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP);
Check that ur base64 encoded string does not start with data:image/jpg;base64,. If it does then remove it. The Base64.decode won't be able to decode it in this case. u can remove it by using encodedString.substring(encodedString.indexOf(",") + 1);. Let me know if this solves ur problem.
Try this,
ImageView driverImage = (ImageView) driverReportView.findViewById(R.id.imgViewDriverImage);
try {
byte [] encodeByte = Base64.decode(driverImageString.replace("\'/", "/"), Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
if (bitmap != null)
driverImage.setImageBitmap(bitmap);
}catch (Exception ex){
Log.e(TAG,"Error to display driver info "+ex.toString());
}
Where
driverImageString is your image string

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.

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.");
}

Loading a URL image for a Live WallPaper

Hey there- I'm attempting to load an image within a Live Wallpaper via a URL... is it possible? If so can you tell my why this code isn't working (Log - "Could not load Bitmap from: " + url)? Thanks!
Engine - Runnable - run():
...
c = holder.lockCanvas();
if (c != null) {
try {
final Bitmap b = BitmapUtils.loadBitmap("http://mw2.google.com/mw-panoramio/photos/medium/17287086.jpg");
c.drawBitmap(b, 0, 0, null);
} catch (Exception e) {
Log.e("Debug", e.toString());
}
}
...
BitmapUtils
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
Yes, it is possible. I do it all the time. :-)
Probably your "issue" is that you have neglected to put
<uses-permission android:name="android.permission.INTERNET" />
in your AndroidManifest.xml

Saving image, webview, 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.

Categories

Resources