Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The problem class:
public class problem extends Activity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.problem);
iv=(ImageView) findViewById(R.id.imageView1);
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm=(Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bm);
}
}
This is what I wanted to do:
Take multiple photos
show them in the screen
store them in the mysql databse.
I am new to android please tell me how to do that.I searched.But I could not find a answer.
From this code IT TAKE ONLY ONE PHOTO.
Show Image on Screen Before Saving :
Use my Code. I am taking a picture using camera intent and before saving it to gallery , it is showed to the user with a Save and Cancel Button :- Call Camera Intent :-
// This code is to call the camera intent. Basically it will start your camera. Put this code in a button or something
String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator +CommonFunction.getDateTime()+".jpg"; // Get File Path
Intent takePictureFromCameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
takePictureFromCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(SD_CARD_TEMP_DIR)));
startActivityForResult(takePictureFromCameraIntent, 123);
onActivityResult : -
// This function is called when you come back to your activity after the intent has finished. Do read android documentation on Google. It will Help
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_RESULT)
{
if (resultCode == Activity.RESULT_OK)
{
String galleryImatePath = SD_CARD_TEMP_DIR; // make SD_CARD_TEMP_DIR Global so that you can access it here from camera intent or pass it in put Extra method and retrieve it here
File f = new File(galleryImatePath);
try {//This code will rotate your image if you have taken the image by rotating the camera
Bitmap cameraBitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inPurgeable = true;
bmOptions.inBitmap = cameraBitmap;
bmOptions.inMutable = true;
cameraBitmap = BitmapFactory.decodeFile(galleryImatePath,bmOptions);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
//To Rotate image Code
ExifInterface exif = new ExifInterface(galleryImatePath);
float rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
System.out.println(rotation);
float rotationInDegrees = exifToDegrees(rotation);
System.out.println(rotationInDegrees);
Matrix matrix = new Matrix();
matrix.postRotate(rotationInDegrees);
final Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap , 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
FileOutputStream fos=new FileOutputStream(galleryImatePath);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.write(bos.toByteArray());
cameraBitmap.recycle();
System.gc();
fos.flush();
fos.close();
// To set image in imageview in dialog. This code will set your image in a custon dialog box "captiondialog". It will contain a full width and height imageview and two textviews - done and cancel. It is upto u what you want to define in the textview's click listener. For example, you can pass the storing image in database in the "Done" textview and "Cancel" textview will dismiss your captiondialog and you app will return to your activity
Capdialog = new Dialog(AddToDo.this,android.R.style.Theme_NoTitleBar_Fullscreen);
Capdialog.setContentView(R.layout.captiondialog);
Capdialog.setCancelable(false);
TextView cancel = (TextView) Capdialog
.findViewById(R.id.cancel);
TextView done = (TextView) Capdialog.findViewById(R.id.done);
Capdialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
ImageView img = (ImageView) Capdialog.findViewById(R.id.image);
img.setImageBitmap(rotatedBitmap);
}
catch(Exception e){}
}
}
}
implement your done and cancel on click listener - what you want to do in them. My code will capture your image, rotate it in the right direction irrespective of camera rotation and show it to you in a dialog before saving it
This code will store your image in DB.You have to use "blob" to store image.. Use This Code :-
public void insertImageInDb(int id , Bitmap img ) {
byte[] data = bos.toByteArray(); // Use This or the code in comments below
/* ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
byte[] data = outputStream.toByteArray();*/
insertStatement_logo.bindLong(1, id);
insertStatement_logo.bindBlob(2, data);
insertStatement_logo.executeInsert();
insertStatement_logo.clearBindings() ;
}
There's an alternative intent action for the device camera that launches the camera in still image mode and does not exit until the user is finished with the activity:
Intent intent = new Intent(
MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
this.startActivity(intent);
Used with a ContentObserver this was exactly what I needed to accomplish. or Handle this in ActivityResult.
Note :- if you are new to android, this is too hard for you to understand now. Please read the android documentation first on google and read tutorials. Make basic apps. Learn first
Related
I have written below codes where when user click attach button to select photos.
Below is code for same.
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select file to upload "), 1);
Below is code for OnActivityResult
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (null != data) { // checking empty selection
if (null != data.getClipData()) { // checking multiple selection or not
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
Uri uri = data.getClipData().getItemAt(i).getUri();
Log.i(TAG, "Path" + getPath(uri));
filespath.add(getPath(uri));
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(getPath(uri), options);
bitmaps.add(bitmap);
}
} else {
Uri uri = data.getData();
}
}
}
}
Now user can select multiple photos and I realized that when photos are more than 10, I get warning too much work done on main thread. when user click on Done button after selecting photos, I have Recycler view where I am showing thumbnail of images selected by user before final upload.
Now issue is when user click Done and till it shows Thumbnail, how can I show ProgressDialog , handle freeze screen and avoid warning work done on main thread.
To keep the parsing and loading work off the main thread you can just wrap everything in an AsyncTask. Given the small amount of code shown, I don't know what functions do what in the above, so this might have to be adjusted a bit. Move all the parsing logic, etc to do in the background as such:
AsyncTask<Void, Void, List<Bitmap>>() {
#Override
protected void onPreExecute()
{
//show progress dialog
//Are you trying to prevent the user from clicking on the UI while updating?
//You can do something such as:
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
#Override
protected List<Bitmap> doInBackground(Void... voids) {
//perform the logic, this will return a list of all the Bitmaps to onPostExecute
//Do NOT perform any ui logic here.
}
#Override
protected void onPostExecute(List<Bitmap> bitmaps) {
//cancel progress dialog.
//Update the UI with the response.
//Clear the window lock:
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
}
};
Having some trouble figuring out how to set the imageview to the picture I just captured with the camera. Would be a bonus if there was some way to display multiple captured pictures at once. Whenever I click the button, a previous image captured appears, then the camera opens, which isn't right. Id like the imageview to be blank, I click the button, take a picture, then that picture is displayed in the imageview. I believe that this line is out of place, but i'm unsure as to how/ where to move it. mimageView.setImageURI(outputFileUri);
public class cameraclass extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
final ImageView mimageView;
mimageView = (ImageView) this.findViewById(R.id.image_from_camera);
// Here, we are making a folder named picFolder to store
// pics taken by the camera using this application.
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
Button capture = (Button) findViewById(R.id.take_image_from_camera);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Here, the counter will be incremented each time, and the
// picture taken by camera will be stored as 1.jpg,2.jpg
// and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
}
catch (IOException e)
{
}
//Uri outputFileUri = Uri.fromFile(newfile);
Uri outputFileUri = FileProvider.getUriForFile(getApplicationContext() , "com.example.android.com220finalapp.provider", newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, TAKE_PHOTO_CODE);
mimageView.setImageURI(outputFileUri);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
Log.d("CameraDemo", "Pic saved");
}
}
}
I believe that this line is out of place, but i'm unsure as to how/ where to move it.
startActivityForResult() is asynchronous. Your photo will not have been taken by the time that method returns. You need to load the image into the ImageView in onActivityResult(), if you got a RESULT_OK response.
However, while setImageURI() may work, it has never been an especially good idea, as it will freeze your app for a while as it loads the photo. There are many image loading libraries for Android that will handle loading your ImageView asynchronously.
I want the picture to go straight to the ImageView without saving it to gallery if possible. As shown in the screenshot, it will ask to save everytime and will save straight to the gallery. Can this be achieved, or will I have to make my own ImageView camera?
public class Main extends Activity {
ImageView ivPhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivPhoto = (ImageView) findViewById(R.id.ivPic);
}
public void TakePhoto(View v){
Intent camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camIntent,0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==0){
Bitmap camImage = (Bitmap) data.getExtras().get("data");
ivPhoto.setImageBitmap(camImage);
}
}
Finally got what I wanted. Thanks guys
public class Main extends Activity {
ImageView ivPhoto;
File myFilesDir;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ivPhoto = (ImageView) findViewById(R.id.ivPic);
myFilesDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.example.project/files");
System.out.println (myFilesDir);
myFilesDir.mkdirs();
}
public void TakePhoto(View v){
Intent camIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
camIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(myFilesDir.toString()+"/temp.jpg")));
startActivityForResult(camIntent, 0);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==0){
try {
Bitmap cameraBitmap;
cameraBitmap = BitmapFactory.decodeFile(myFilesDir + "/temp.jpg");
Bitmap.createBitmap(cameraBitmap);
ivPhoto.setImageBitmap(cameraBitmap);
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
From my understanding you don't want this to be showing up by any media scanner, like the gallery application. What you should actually do is not store it in a root directory like pictures or sdcard, but store it in your applications data folder in the sdcard in Android/data/package/.
You can get this using: http://developer.android.com/reference/android/content/Context.html#getExternalFilesDir(java.lang.String)
File myFilesDir = getExternalFilesDir(null);
OR
File myFilesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Note that it will only work on API versions 8 or above.
If you don't want to use the function you can simply just use:
File myFilesDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/" + packageName + "/files");
myFilesDir.mkdirs();
Use my Code. I am taking a picture using camera intent and before saving it to gallery , it is showed to the user with a Save and Cancel Button :-
Call Camera Intent :-
String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator +CommonFunction.getDateTime()+".jpg"; // Get File Path
Intent takePictureFromCameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
takePictureFromCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(SD_CARD_TEMP_DIR)));
startActivityForResult(takePictureFromCameraIntent, 123);
onActivityResult : -
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_RESULT)
{
if (resultCode == Activity.RESULT_OK)
{
String galleryImatePath = SD_CARD_TEMP_DIR; // make SD_CARD_TEMP_DIR Global so that you can access it here from camera intent or pass it in put Extra method and retrieve it here
File f = new File(galleryImatePath);
try {
Bitmap cameraBitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inPurgeable = true;
bmOptions.inBitmap = cameraBitmap;
bmOptions.inMutable = true;
cameraBitmap = BitmapFactory.decodeFile(galleryImatePath,bmOptions);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
//To Rotate image Code
ExifInterface exif = new ExifInterface(galleryImatePath);
float rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
System.out.println(rotation);
float rotationInDegrees = exifToDegrees(rotation);
System.out.println(rotationInDegrees);
Matrix matrix = new Matrix();
matrix.postRotate(rotationInDegrees);
final Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap , 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
FileOutputStream fos=new FileOutputStream(galleryImatePath);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.write(bos.toByteArray());
cameraBitmap.recycle();
System.gc();
fos.flush();
fos.close();
// To set image in imageview in dialog
Capdialog = new Dialog(AddToDo.this,android.R.style.Theme_NoTitleBar_Fullscreen);
Capdialog.setContentView(R.layout.captiondialog);
Capdialog.setCancelable(false);
TextView cancel = (TextView) Capdialog
.findViewById(R.id.cancel);
TextView done = (TextView) Capdialog.findViewById(R.id.done);
Capdialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
ImageView img = (ImageView) Capdialog.findViewById(R.id.image);
img.setImageBitmap(rotatedBitmap);
}
catch(Exception e){}
}
}
}
implement your done and cancel on click listener - what you want to do in them.
My code will capture your image, rotate it in the right direction irrespective of camera rotation and show it to you in a dialog before saving it
Google provided a tutorial on this exact topic: Controlling the Camera
So I've got my image to successfully pass to a URI...however I don't know how to save it or convert it to a bitmap while still maintaining resolution. Any suggestions? Thank you.
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// CALL THE PICTURE (this works)
File t = new File (STORAGE_PATH + "savedAndroid.jpg");
mURI = Uri.fromFile(t);
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mURI);
startActivityForResult(i,0); //0 is default camera
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
imageView.setImageURI(mURI); //this seems to work...by itself
//save the image or convert it to a bitmap to use with tesseract...
}
InputStream is = context.getContentResolver().openInputStream(mURI);
Bitmap bitmap = BitmapFactory.decodeStream(is, null, new BitmapFactory.Options());
Then use it however you want.
Hope this helps.
I take a picture in Android via
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, CAMERA_REQUEST);
and show / save it via
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView theImage = (ImageView) findViewById(R.id.preview);
theImage.setImageBitmap(photo);
// try to save its
try {
File testFile = new File(Environment.getExternalStorageDirectory(), "test.png");
testFile.createNewFile();
FileOutputStream out = new FileOutputStream(testFile);
photo.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
This works fine, however the quality of the image is very bad. I do not know why, since I take the picture with 8 mega pixels.
Is there a way to do this without requiring the camera manually?
Take a closer look at this post: there are two ways to capture an image in Android. First one is designed for taking small and lightweight pictures - that's the approach you use, and the second one captures full-sized pictures and writes them to storage. The post describes both ways of accomplishing this task.