I have a imageview field in my android app, onclick of the same I have given a "open camera" functionality and the user can click the photo from camera and it gets uploaded to ImageView
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(user_image.getDrawable() == null ){
Toast.makeText(NewCall4.this, "No image uploaded", Toast.LENGTH_SHORT).show();
}
else{
Intent i=new Intent(NewCall4.this,NewCall5.class);
startActivity(i);
}
}
}
);
What I want is, if I am not uploading the image in the imageview then it should give the error/toast message as "Image not uploaded"
You Can check the Drawable if attached to ImageView
Imageview imageView = (ImageView)findViewById(R.id.image);
if(imageView.getDrawable() == null){
//Then Nothing is attached with imageviw
}
It is so simple. When You call Intent for camera open it gives callback in onActivityResult in that just pass the value of the image. And check it is null or not in the click event.
Example :-
=> To Open Camera :-
Intent intent1 = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, camera);
You will get a callback in onActivityResult
=> onActivityResult :- ( I am getting actual Image path here)
if (resultCode == RESULT_OK && requestCode == camera) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
addprofile.setImageBitmap(photo); // set image to imageview
Uri tempUri = getImageUri(getApplicationContext(), photo);
File finalfile = new File(getrealpathfromuri(tempUri));
imagepath = finalfile.toString(); // imagepath is a global variable
}
private Uri getImageUri(Context applicationContext, Bitmap photo) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(applicationContext.getContentResolver(),photo,"Title",null);
return Uri.parse(path);
}
private String getrealpathfromuri(Uri tempUri) {
String path = "";
if(getContentResolver() != null){
Cursor cursor = getContentResolver().query(tempUri, null, null, null, null);
if(cursor != null){
cursor.moveToFirst();
int idk = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idk);
cursor.close();
}
}
return path;
}
Finally imagepath has an actual path of the image.
=> Check imagepath null or not :- (in event)
if (imagepath == null) {
Toast.makeText(this, "Please Select FileImage", Toast.LENGTH_SHORT).show();
}
Hi you can try something like this
Imageview img = (ImageView)findViewById(R.id.image){
img .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, id);
}
});
And OnResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap photo = (Bitmap) data.getExtras().get(“data”);
img.setImageBitmap(photo);
}
Related
This is my code. I want to add one more button here which onclick send the image to next activity , but I am not able to configure this. How should I do it?
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
Initially, keep newly added button disable and in onActivityResult method after getting image string enable button and set onClickListener to button. And pass that image string to next activity using intent extra.
In onActivityResult method,
newButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),NextActivity.class).putExtra("img",imgDecodableString));
}
});
Best way to do this with large image would be using Serializable, since Intent and Parcelable both have size limit.
Answers to this question might help : Serializing and De-Serializing android.graphics.Bitmap in Java
you can put the data in your first activity like
Intent intent = new Intent(this, NewActivity.class);
intent.putExtra("BitmapImage", bitmap);
and in second activity parse the data like below:
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
convert your imagepath to bitmap code snipped is:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
//First Activity
Bitmap b = null;
String bitmapString = getStringFromBitmap(b);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bitmapString", bitmapString);
//Second Activity
String receivedBitmapString = getIntent().getStringExtra("bitmapString");
Bitmap receivedBitmap = getBitmapFromString(receivedBitmapString);
//Functions
private String getStringFromBitmap(Bitmap bitmapPicture) {
/*
* This functions converts Bitmap picture to a string which can be
* JSONified.
* */
final int COMPRESSION_QUALITY = 100;
String encodedImage;
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY,
byteArrayBitmapStream);
byte[] b = byteArrayBitmapStream.toByteArray();
encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
return encodedImage;
}
private Bitmap getBitmapFromString(String jsonString) {
/*
* This Function converts the String back to Bitmap
* */
byte[] decodedString = Base64.decode(stringPicture, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
}
Source:Link
I'm new to android and to java trying to learn my way in.
Right now I am trying to achieve (A)Select image form gallery (B) show a preview and ( C ) activity is Uploading to server:
Select image form gallery and show a preview: done (achieved) by using below Code
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// call android default gallery
startActivityForResult(intent, PICK_FROM_GALLERY);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {if (requestCode == PICK_FROM_GALLERY) {
if (resultCode == RESULT_OK) {
fileUri = data.getData();
filePath = getRealPathFromURI(getApplicationContext(), fileUri);
Intent imagePreview = new Intent(MainActivity.this, ImagePreview.class);
imagePreview.putExtra("filePath", filePath);
startActivity(imagePreview);
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}}
}
And In ImagePreview.java
Intent imagePreview = getIntent();
// image or video path that is captured in previous activity
filePath = imagePreview.getStringExtra("filePath");
displayImage(filePath);
private void displayImage(String filePath) {
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageBitmap(BitmapHelper.decodeSampledBitmap(filePath, 300, 250));
Now According to my understanding, since the filePath is already a string, I should be able it pass it to uploadactivity.java as such
private void upload(){
Intent upload = new Intent(ImagePreview.this, UploadActivity.class);
upload.putExtra("finalImage", filePath);
startActivity(upload);
}
and in uploadactivity.java
Intent upload = getIntent();
// image or video path that is captured in previous activity
finalImage = upload.getStringExtra("finalImage");
By this I can get to UpoloadActivity and upload button is displayed but filePath is not passed.
What am I doing wrong?
You're not using the same key for the extras:
upload.putExtra("finalImage", filePath);
upload.getStringExtra("filePath");
Replace
finalImage = upload.getStringExtra("filePath");
with
finalImage = upload.getStringExtra("finalImage");
I want to save image uri from taking camera or gallery into SQLite.
And I want to display the image which called uri from SQLite.
If I want to do this, someone said you have to save image uri into SQLite as byte, and
you can set image on imageView.
I understand the theory, but I am still getting stuck with my coding.
If it is true, I want to save formatted image into sdcard or somewhere.
someone said use BitmapFactory and decodeResource.
and call the uri from R.drawable.
However, I don't know how to save image into R.drawable folder.
Could you help me? I will give you some my coding.
I am fighting with saving image into SQLite and how to load it, and how to modify it during two weeks!
Sorry for really long coding. I don't know where I am now.
Thank you.
fridgeDetails.java
populateFields();
private void populateFields()
{
if (mRowId != null)
{
Cursor data = mDbHelper.fetchItem(mRowId);
startManagingCursor(data);
//load image from sqlite
byte[] blob = data.getBlob(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_IMAGE));
mImageView.setImageBitmap(BitmapFactory.decodeByteArray(blob, 0, blob.length));
nameEdit.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_NAME)));
categoryEdit.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_CATEGORY)));
expired_Date_Btn.setText(data.getString(data.getColumnIndexOrThrow(FridgeDbAdapter.KEY_EXPIRED_DATE)));
}
else{
expired_Date_Btn.setText(
new StringBuilder()
.append(mDay).append("/")
//month is 0 based. Then add 1
.append(mMonth + 1).append("/")
.append(mYear).append(" "));
}
}
//create dialog for taking image
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
if(item==0)
{
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, PICK_FROM_CAMERA);
}
catch(ActivityNotFoundException e)
{
e.printStackTrace();
}
}
else
{
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
//image chooser
startActivityForResult(Intent.createChooser(galleryIntent, "Complete action using"), PICK_FROM_GALLERY);
}
}
});
confirmButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
//set alarm with expiration date
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setOneTimeAlarm();
Toast.makeText(fridgeDetails.this, "Alarm automatic set", Toast.LENGTH_SHORT).show();
saveState();
setResult(RESULT_OK);
finish();
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK) return;
switch (requestCode)
{
case PICK_FROM_CAMERA:
Bundle extras = data.getExtras();
Bitmap selectedImage = (Bitmap) extras.get("data");
selectedImage = Bitmap.createScaledBitmap(selectedImage, 200, 200, false);
mImageView.setImageBitmap(selectedImage);
break;
case PICK_FROM_GALLERY:
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
Bitmap bt=Bitmap.createScaledBitmap(bitmap, 200, 200, false);
mImageView.setImageBitmap(bt);
break;
}
}
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
saveState();
}
#Override
protected void onPause()
{
super.onPause();
saveState();
}
#Override
protected void onResume()
{
super.onResume();
populateFields();
}
private void saveState()
{
String name = (String) nameEdit.getText().toString();
String category = (String) categoryEdit.getText().toString();
String expired_date = (String) expired_Date_Btn.getText().toString();
byte[] image = ConvertDrawableToByteArray(mImageView.getDrawable());
if(mRowId == null)
{
long id = mDbHelper.insertItem(category, name, expired_date, image);
if(id>0)
{
mRowId = id;
}
}
else
{
mDbHelper.updateItem(mRowId, category, name, expired_date, image);
}
}
public static byte[] ConvertDrawableToByteArray(Drawable drawableResource) {
Bitmap imageBitmap = ((BitmapDrawable) drawableResource).getBitmap();
ByteArrayOutputStream imageByteStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, imageByteStream);
byte[] imageByteData = imageByteStream.toByteArray();
return imageByteData;
}
The location of your image file can be obtained from data.getData() in OnActivityResult method. You can save the location as a string in Sqlite. Then use
imageView.setImageBitmap(BitmapFactory.decodeFile(filename)
to show the image.
The default location is your app folder. If you want to store elsewhere, pass the location as in the foll code
// 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)
For more info see - http://developer.android.com/guide/topics/media/camera.html
Check this to Get the URI of Captured image
Check this for Inserting image to DB as BLOB and Retrieve it back and display.
It includes download image from Server and insert into DB, just change as it as per your requirement.
I am using this code to fetch Image from gallery:
fromGalleryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
canvasPictureDialog.dismiss();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
//startActivity(intent);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),10);
//finish();
}
});
And to take image from camera i use this code:
private static final int TAKE_PHOTO_CODE = 1;
private void takePhoto(){
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(this)) );
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
private File getTempFile(Context context){
//it will return /sdcard/image.tmp
//final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName() );
final File path = new File( Environment.getExternalStorageDirectory(), context.getPackageName());
if(!path.exists()){
path.mkdir();
}
return new File(path, "image.tmp");
}
And common code for onActivityResult is:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 10 && resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
//Bitmap croppedImage = BitmapFactory.decodeFile(imagePath);
tempBitmap = BitmapFactory.decodeFile(imagePath);
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
}
if(resultCode == RESULT_OK && requestCode==TAKE_PHOTO_CODE){
final File file = getTempFile(this);
try {
tempBitmap = Media.getBitmap(getContentResolver(), Uri.fromFile(file) );
photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
// do whatever you want with the bitmap (Resize, Rename, Add To Gallery, etc)
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now with using this code i am drawing the image on canvas:
if(!(imagePath==null))
{
//tempBitmap = BitmapFactory.decodeFile(imagePath);
//photoBitmap = Bitmap.createScaledBitmap(tempBitmap, display.getWidth(), display.getHeight(), true);
canvas.drawBitmap (photoBitmap,0, 0, null);
}
But with that use, I am able to get Image from gallery but not from the camera. Why ??
Whats wrong in my code ??
Thanks.
Well, I have solve this problem for my own way.
There is a logical mistake. I have taken the if condition on imagePath variable which can not works for the taking image from camera.
I have taken one boolean Variable and set it for Taking Image from Camera and it works for me.
Anyway, Thanks for the Comments and help.
Thanks.
I implemented the application for getting image from the camera album in sdcard.But it is not working properly.
Here Intent returns like this Intent { act=com.htc.HTCAlbum.action.ITEM_PICKER_FROM_COLLECTIONS dat=content://media/external/images/media/9 typ=image/jpeg (has extras) }
In the code
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
Here (Bitmap) data.getExtras().get("data")
this part returns null.
How to get the bitmap here please can anybody help me.
Code:
cam_images_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent cam_ImagesIntent = new Intent(Intent.ACTION_GET_CONTENT);
cam_ImagesIntent.setType("image/*");
startActivityForResult(cam_ImagesIntent, CAMERA_IMAGES_REQUEST);
}
});
if(requestCode == CAMERA_IMAGES_REQUEST && resultCode==Activity.RESULT_OK)
{
System.out.println("data(CAMERA_IMAGES_REQUEST):"+data);
if(data != null)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
System.out.println("Bitmap(CAMERA_IMAGES_REQUEST):"+thumbnail);
System.out.println("cap_image(CAMERA_IMAGES_REQUEST):"+cap_image);
cap_image.setImageBitmap(thumbnail);
}
else
{
System.out.println("SDCard have no images");
Toast.makeText(camera.this, "SDCard have no images", Toast.LENGTH_SHORT);
}
}
thanks
Do the following in your code:
if(data != null)
{
Uri selectedImageUri = data.getData();
filestring = selectedImageUri.getPath();
Bitmap thumbnail = BitmapFactory.decodeFile(filestring, options2);
System.out.println("Bitmap(CAMERA_IMAGES_REQUEST):"+thumbnail);
System.out.println("cap_image(CAMERA_IMAGES_REQUEST):"+cap_image);
cap_image.setImageBitmap(thumbnail);
}
This should work.
Edit:
Also if you want a "thumbnail" do the following:
Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(
getContentResolver(), selectedImageUriId,
MediaStore.Images.Thumbnails.MICRO_KIND,
(BitmapFactory.Options) null);
Well the way go about doing this is very easy, just:
//Get incoming intent
Intent intent = getIntent();
intent.setType("image/*");
String action = intent.getAction();
String type = intent.getType();
if(Intent.ACTION_SEND.equals(action) && type != null){
handleIncomingData(intent);
}
public void handleIncomingData(Intent data){
Uri imageSelected = data.getParcelableExtra(Intent.EXTRA_STREAM);
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageSelected);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
Remember to put this code after everything is initialized first or else you will get a NullPointerException. I prefer to put it at the bottom of the onCreate()
This problem can be solved by writing fewer lines of codes.
if(requestCode== your_request_code){
if(resultCode==RESULT_OK){
Uri uri = data.getData(); //<----get the image uri
imageView.setImageURI(uri); //<----set the image uri
}
I have this code:
public void onGalleryRequest() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent,
getResources().getString(R.string.selectImage)),
GALLERY_REQ);
}
and then in onActivityResult I make this test:
if (requestCode == CAMERA_PIC_REQUEST && data != null
&& resultCode != 0)
it works for me api level 7