I am using the ZXing library for barcode scanning.
I want to scan a barcode using this library from an image (e.g., on the SD card) rather than from the camera.
How can I do this using the ZXing library?
I wanted to test it out before posting it so it took me a while, I'm also using ZXing right now so this comes handy for me as well:
First of course, read the image from the gallery (this can be in your activity):
Intent pickIntent = new Intent(Intent.ACTION_PICK);
pickIntent.setDataAndType( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(pickIntent, 111);
After that, just get the image uri on the activity result and then ZXing will do the magic:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
//the case is because you might be handling multiple request codes here
case 111:
if(data == null || data.getData()==null) {
Log.e("TAG", "The uri is null, probably the user cancelled the image selection process using the back button.");
return;
}
Uri uri = data.getData();
try
{
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
if (bitmap == null)
{
Log.e("TAG", "uri is not a bitmap," + uri.toString());
return;
}
int width = bitmap.getWidth(), height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
bitmap.recycle();
bitmap = null;
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap bBitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
try
{
Result result = reader.decode(bBitmap);
Toast.makeText(this, "The content of the QR image is: " + result.getText(), Toast.LENGTH_SHORT).show();
}
catch (NotFoundException e)
{
Log.e("TAG", "decode exception", e);
}
}
catch (FileNotFoundException e)
{
Log.e("TAG", "can not open file" + uri.toString(), e);
}
break;
}
}
I tested this and it works, cheers.
Related
I'm building an app that require method to take picture from in-app camera, but for some Android devices (old device or low ram), it's quite freeze when taking picture triggered. Is there any code i can modify or optimize to make user experience feels better?
//this function trigger to take picture (or screenshot) from user screen
private void captureImage() {
mPreview.setDrawingCacheEnabled(true);
final Bitmap[] drawingCache = {Bitmap.createBitmap(mPreview.getDrawingCache())};
mPreview.setDrawingCacheEnabled(false);
mCameraSource.takePicture(null, bytes -> {
int orientation = Exif.getOrientation(bytes);
Bitmap temp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Bitmap picture = rotateImage(temp, orientation);
assert picture != null;
Bitmap overlay = Bitmap.createBitmap(mGraphicOverlay.getWidth(), mGraphicOverlay.getHeight(), picture.getConfig());
Canvas canvas = new Canvas(overlay);
Matrix matrix = new Matrix();
matrix.setScale((float) overlay.getWidth() / (float) picture.getWidth(), (float) overlay.getHeight() / (float) picture.getHeight());
// mirror by inverting scale and translating
matrix.preScale(-1, 1);
matrix.postTranslate(canvas.getWidth(), 0);
Paint paint = new Paint();
canvas.drawBitmap(picture, matrix, paint);
canvas.drawBitmap(drawingCache[0], 0, 0, paint);
//this function to save picture taken and put it on app storage cache
try {
String mainpath = getApplicationContext().getFilesDir().getPath() + separator + "e-Presensi" + separator;
File basePath = new File(mainpath);
if (!basePath.exists())
Log.d("CAPTURE_BASE_PATH", basePath.mkdirs() ? "Success" : "Failed");
//this function to get directory path of saved photo
String path = mainpath + "photo_" + getPhotoTime() + ".jpg";
String namafotoo = "photo_" + getPhotoTime() + ".jpg";
filePath = path;
namafoto = namafotoo;
SessionManager.createNamaFoto(namafoto);
File captureFile = new File(path);
boolean sucess = captureFile.createNewFile();
if (!captureFile.exists())
Log.d("CAPTURE_FILE_PATH", sucess ? "Success" : "Failed");
FileOutputStream stream = new FileOutputStream(captureFile);
overlay.compress(Bitmap.CompressFormat.WEBP, 60, stream);
stream.flush();
stream.close();
if (!picture.isRecycled()) {
picture.recycle();
}
if (drawingCache[0] != null && !drawingCache[0].isRecycled()) {
drawingCache[0].recycle();
drawingCache[0] = null;
}
mPreview.setDrawingCacheEnabled(false);
uploadPicture();
finish();
} catch (IOException e) {
e.printStackTrace();
}
});
}
Thanks for your help.
In general, I would advise you to step through your code and look at large memory resources you're generating on each line and consider setting those to null aggressively as you move throughout the method if you're done.
For example, you have a variable called temp which is size "Y" bytes that you appear to rotate and then never use temp after that. If picture is a rotated copy of temp then you have now used 2Y bytes of memory to keep temp and picture. I suspect if you simply set temp to null after creating picture, you might free up half that memory that your older/slower phones are going to badly need.
Take that same concept and follow through with the rest of your method to see if you can find other optimizations. Basically anywhere you're creating a copy of the image data you're not going to use, you should immediately set it to null so the garbage collector can throw it away aggressively.
Firt you need some variables:
byte[] byteArray_IMG;
String currentPhotoPath;
static final int REQUEST_TAKE_PHOTO = 1;
ImageView imageView; // maybe you need show the photo before send it
Then define the method to take the photo:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
Toast.makeText(getApplicationContext(),Error takin the photo",Toast.LENGTH_LONG).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
path_img = photoFile.toString();
Uri photoURI = FileProvider.getUriForFile(this,"com.app.yournmamepackage.fileprovider" , photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
Create the method to create the file image
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
Override the activity result to:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
/* Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byteArray_IMG = stream.toByteArray();*/
MediaScannerConnection.scanFile(this, new String[]{path_img}, null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
Log.i("path",""+path);
}
});
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap imageBitmap = BitmapFactory.decodeFile(path_img);
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 14, stream);
imageView.setImageBitmap(imageBitmap);
byteArray_IMG = stream.toByteArray();
}
}
Remember this is very important
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 25, stream)
// 25 is photo quality 0-100
Then you can upload the picture usin an asynchronous process
Firstly Initialize these variables above onCreate() method in your activity/fragment
val FILE_NAME:String="photo.jpg" //give any name with.jpg extension
private var imageuri: Uri?=null
val REQUEST_IMAGE=111
Now open camera
val intent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
photofile = getphotofile(FILE_NAME)
imageuri = activity?.let { it1 -> FileProvider.getUriForFile(it1, "//your package name here//.fileprovider", photofile) } //put your package name
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri)
startActivityForResult(int, REQUEST_IMAGE)
onActivityResult() method
if(requestCode==REQUEST_IMAGE && resultCode == Activity.RESULT_OK){
val progressdialog: ProgressDialog = ProgressDialog(activity)
progressdialog.setTitle("Sending Image....")
progressdialog.show() //start your progressdialog
val ref= FirebaseDatabase.getInstance().reference
val messagekey=ref.push().key //create a key to store image in firebase
var bmp: Bitmap?=null
try {
bmp=MediaStore.Images.Media.getBitmap(activity?.contentResolver,imageuri) //get image in bitmap
} catch (e: IOException) {
e.printStackTrace();
}
val baos= ByteArrayOutputStream()
bmp!!.compress(Bitmap.CompressFormat.JPEG,50,baos) //compress the quality of image to 50 from 100
val fileinBytes: ByteArray =baos.toByteArray()
val store: StorageReference = FirebaseStorage.getInstance().reference.child("Chat Images/") //create a child reference in firebase
val path=store.child("$messagekey.jpg") //store a message in above reference with the unique key created above with .jpg extension
val uploadTask: StorageTask<*>
uploadTask=path.putBytes(fileinBytes) //it will upload the image to firebase at given path
uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
Toast.makeText(activity, "Upload Failed", Toast.LENGTH_SHORT).show()
}
return#Continuation path.downloadUrl
}).addOnCompleteListener { task->
if(task.isSuccessful){
url=task.result.toString() //get the url of uploaded image
//Do what you want with the url of your image
progressdialog.dismiss()
Toast.makeText(activity, "Image Uploaded", Toast.LENGTH_SHORT).show()
}
}.addOnFailureListener { e->
progressdialog.dismiss()
Toast.makeText(activity, "Failed " + e.message, Toast.LENGTH_SHORT)
.show();
}
uploadTask.addOnProgressListener { task->
var progress:Double=(100.0*task.bytesTransferred)/task.totalByteCount
progressdialog.setMessage("Sending ${progress.toInt()}%") //this will show the progress in progress bar 0-100%
}
}
I have been uploading images to FirebaseStorage, but often they are the wrong way around when displaying them. I have discovered the ExifInterface that can determined the orientation of the image and rotate and flip it if necessary.
When selecting the image from the gallery area on my phone I get this error.
I can select the image on my phone from the gallery and It can be displayed on the page.
The differences between the URI address and the data is one /
Data.getData() address : content://media/external/images/media/53331
uri.toString() address: content:/media/external/images/media/53331
I'm using the uri address as the images absolute path of the image to be able to rotate it if necessary. I pass this value into another method called modifyOrientation which then rotates it. Once it is passed into the method it reaches the line
ExifInterface ei = new ExifInterface(image_absolute_path);
and then returns to the catch as the file was not found.
Below is the entire error I'm getting as well as all my code. How can I fix this issue that I'm having. So when I pass the URI across into the next method it actually has the correct address.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
final FirebaseUser user = auth.getCurrentUser();
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK)
{
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Displaying Image...");
progressDialog.show();
//imageUri = data.getData();
//Picasso.get().load(imageUri).into(profileImage);
final Uri uri = data.getData();
File file = new File(uri.toString());
file.getAbsolutePath();
progressDialog.dismiss();
try
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
modifyOrientation(bitmap,file.getAbsolutePath());
profileImage.setImageBitmap(bitmap);
}
catch(IOException e)
{
e.getStackTrace();
}
}
}
public static Bitmap modifyOrientation(Bitmap bitmap, String image_absolute_path) throws IOException {
ExifInterface ei = new ExifInterface(image_absolute_path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotate(bitmap, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotate(bitmap, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotate(bitmap, 270);
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
return flip(bitmap, true, false);
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
return flip(bitmap, false, true);
default:
return bitmap;
}
}
public static Bitmap rotate(Bitmap bitmap, float degrees) {
Matrix matrix = new Matrix();
matrix.postRotate(degrees);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
public static Bitmap flip(Bitmap bitmap, boolean horizontal, boolean vertical) {
Matrix matrix = new Matrix();
matrix.preScale(horizontal ? -1 : 1, vertical ? -1 : 1);
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
A Uri is not a File.
Step #1: Delete File file = new File(uri.toString());
Step #2: Make sure that you are using the Support Library edition of ExifInterface
Step #3: Call getContentResolver() on your Activity to get a ContentResolver
Step #4: Call openInputStream() on the ContentResolver, passing in the Uri, to get an InputStream on the content pointed to by that Uri
Step #5: Pass that InputStream to the ExifInterface constructor
Step #6: Use that ExifInterface as you are presently, to determine the image orientation
Step #7: Once you get things working, move all of this I/O to a background thread
In my android application i need to take a picture. The first picture goes fine and uploads great to the server so it can be sent by email to the user. That's working fine. Yet when i want to upload an 2nd image it says Out Of Memory Exception. I don't know why, but somehow it does.
My logcat output can be found at this pastebin link: http://pastebin.com/uVduy3d9
My code for handling the image is as following:
First check if phone has a camera:
Camera cam = Camera.open();
if (cam != null) {
if (savedInstanceState != null
&& savedInstanceState.getBoolean("Layout")) {
setContentView(R.layout.registration_edit);
initializeAccountDetails((User) savedInstanceState
.getSerializable(EXTRA_MESSAGE));
inAccountDetails = true;
} else {
setContentView(R.layout.step_4);
((Button) findViewById(R.id.snap)).setOnClickListener(this);
((Button) findViewById(R.id.rotate)).setOnClickListener(this);
cam.stopPreview();
cam.release();
cam = null;
}
} else {
if (savedInstanceState != null
&& savedInstanceState.getBoolean("Layout")) {
setContentView(R.layout.registration_edit);
initializeAccountDetails((User) savedInstanceState
.getSerializable(EXTRA_MESSAGE));
inAccountDetails = true;
} else {
setContentView(R.layout.step_4b);
}
}
When clicking on the button Snap the following onClick event is fired:
#Override
public void onClick(View v) {
if (v.getId() == R.id.snap) {
File directory = new File(Environment.getExternalStorageDirectory()
+ "/BandenAnalyse/Images/");
if (directory.exists()) {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(),
"/BandenAnalyse/Images/IMG_" + _timeStamp + ".jpg");
_mUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, _mUri);
startActivityForResult(i, TAKE_PICTURE);
} else {
directory.mkdir();
this.onClick(v);
}
} else {
if (_mPhoto != null) {
Matrix matrix = new Matrix();
matrix.postRotate(90);
_mPhoto = Bitmap.createBitmap(_mPhoto, 0, 0,
_mPhoto.getWidth(), _mPhoto.getHeight(), matrix, true);
((ImageView) findViewById(R.id.photo_holder))
.setImageBitmap(_mPhoto);
_mPhoto.recycle();
}
}
}
When the picture is taken the result method will be fired:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
getContentResolver().notifyChange(_mUri, null);
ContentResolver cr = getContentResolver();
try {
_mPhoto = android.provider.MediaStore.Images.Media
.getBitmap(cr, _mUri);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int scale = _mPhoto.getWidth() / width;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inSampleSize = 8;
Debug.out(PATH_TO_PHOTO);
Bitmap temp = BitmapFactory.decodeFile(PATH_TO_PHOTO, o);
_mPhoto = Bitmap.createScaledBitmap(
temp,
_mPhoto.getWidth() / scale, _mPhoto.getHeight()
/ scale, false);
temp.recycle();
((ImageView) findViewById(R.id.photo_holder))
.setImageBitmap(_mPhoto);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT)
.show();
}
}
}
}
The error should be in the last method, as when i'm in the cameramode and want to get back to my application the error occurs.
How to fix this error? Did i miss something?
EDIT:
Added Code in the function: OnActivityResult.
Created a temp object as one of the solutions said. Too bad this didn't help solving the error.
The error Out of memory Exception occurs at the line:
_mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, _mUri);
You shouldn't create a bitmap and using it without keeping a reference on it since you have to release it for good memory management.
what you do :
_mPhoto = Bitmap.createScaledBitmap(
BitmapFactory.decodeFile(PATH_TO_PHOTO, o),
_mPhoto.getWidth() / scale, _mPhoto.getHeight()
/ scale, false);
is bad ! ;)
prefer :
Bitmap temp = BitmapFactory.decodeFile(PATH_TO_PHOTO, o);
_mPhoto = Bitmap.createScaledBitmap(
temp,
_mPhoto.getWidth() / scale, _mPhoto.getHeight()
/ scale, false);
temp.recycle(); //this call is the key ;)
Read your code with in mind : "every bitmap created has to be recycle or it will crash with OOM error at some point".
hope that helps !
you should read more about android Bitmaps and memory management for a complete understanding ;)
in my app a user either picks an image from their image gallery or captures an image with their camera.
When you capture it is added to the gallery of the user.
I have found that the images, besides being the same image have massive changes in size.
Captured: 33kb
CODE:
if (requestCode == TAKEIMAGE) {
System.out.println("TAKE IMAGE");
int photoLength = 0;
Bitmap photo = (Bitmap) data.getExtras().get("data");
photoLength = GetBitmapLength(photo);
SetSubmissionImage(photo, photoLength);
}
Taken from gallery: 1600kb
CODE:
else if (requestCode == CHOOSEIMAGE) {
System.out.println("CHOOSE IMAGE");
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
try {
FileInputStream fileis=new FileInputStream(selectedImagePath);
BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
byte[] bMapArray= new byte[bufferedstream.available()];
bufferedstream.read(bMapArray);
int photoLength = 0;
Bitmap photo = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
bMapArray = null;
fileis.close();
bufferedstream.close();
//rotate to be portrait properly
try {
ExifInterface exif = new ExifInterface(selectedImagePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
}
else if (orientation == 3) {
matrix.postRotate(180);
}
else if (orientation == 8) {
matrix.postRotate(270);
}
photo = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true); // rotating bitmap
}
catch (Exception e) {
}
//photo = GetCompressedBitmap(photo);
photoLength = GetBitmapLength(photo);
SetSubmissionImage(photo, photoLength);
}
Like other said in comments you need to start the camera activity with an intent that contains an uri where image will be saved:
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
Then in your onActivityResult() method you can retrive the uri and load the image the from the URI in the intent.
I had a problem when saving picture on sdcard from my app.
that when i am taking a picture and saving it on sdcard and go to my app and take a new one and save it on sdcard the previous preview picture appear and when view it on my computer it appear corrupted ?
why this problem ?
public static void save(Bitmap bm, String path) {
OutputStream outStream = null;
try {
outStream = new FileOutputStream(new File(path));
bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
bm.recycle();
System.gc();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
enter code here
Use this method to store the image and display it.This is used to store the image
//create new directory to store image
File photo = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/files/Receipt");
boolean success = false;
if(!photo.exists())
{
success = photo.mkdirs();
}
//if exists save the image in specified path
if(!success)
{
dbimgguid = UUID.randomUUID();
imagename =dbimgguid.toString();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photo = new File(Environment.getExternalStorageDirectory()+"/Android/data/"+getApplicationContext().getPackageName()+"/files/Receipt", imagename+".png");
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));
imageurl = Uri.fromFile(photo);
startActivityForResult(intent, CAMERA_RECEIPTREQUEST);
}
To view the image
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
case CAMERA_RECEIPTREQUEST:
if(resultCode== Activity.RESULT_OK)
{
//Toast.makeText(this, "Receipt Image Saved", Toast.LENGTH_SHORT).show();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
ImageView jpgView = (ImageView)findViewById(R.id.imageView1);
Bitmap receipt = BitmapFactory.decodeFile(photo.toString(),options);
jpgView.setImageBitmap(receipt);
}
break;
}
I hope this will help you..
}
Do you have permissions to store to the SD card? I believe you need save and save to sd permissions.