I am picking image from gallery and showing image on ImageView. I am able to do it successfully. My problem is when i try to set an image that are captured from camera(.jpg images) they are not shown in imageview just a blank screen comes up. Even images of type .jpg are successfully showed that are not captured from camera. Can't understand the reason, may be due to larger size. Help please
Following is my code:
public class ImagePick extends Activity {
private Bitmap bitmap;
private ImageView imv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_upload);
imv = (ImageView) findViewById(R.id.targetimage);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file path of selected image
cursor.close();
// Convert file path into bitmap image using below line.
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
imv.setImageBitmap(yourSelectedImage);
}
}
}
}
Thanks in Advance
you need to use FileInputStream and BufferedInputStream to read the image then you convert the image into bitmap.
private FileInputStream is = null;
private BufferedInputStream bis = null;
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
also check the link
Thanks
Instead of:
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file path of selected image
Try:
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
And close the cursor After the BitmapDecoding.
Remember that the access to the SD card should be done in AsynckTasks. And you can resize the image to fit the screen, that way you won't use a lot of memory, take a look at my other answer Bitmap Out Of Memory Issues. on how to do this.
Related
I am working on a module in which user can upload the image to the server. To achieve this, I have to change selected image into Base64. After conversion, I have to use Json POST method to upload image, but every time application crashes and I am getting error in this line..
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
this is my code that I am trying, PLease have a look and let me what mistake I am doing here.
buttonLoadPicture.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imgView);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
ss = BitmapFactory.decodeFile(picturePath);
Log.d("value", ss.toString());
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),ss);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 100, bao);
byte [] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba,Base64.DEFAULT);
encodeToString is not a function in BitmapFactory. You should encode to base64 in a different way. I would like to suggest this answer
I am doing a project in which user select the image and we have to store the path of the image. I am able to display the picture in imageView but when the application closes or user presses back button image is not displaying. So I have to hold the image forever until user deletes the image.
Following is my code:
Button buttonLoadImage = (Button) findViewById(R.id.pre1);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#SuppressWarnings("unused")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath);
//testimage.setImageBitmap(yourSelectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
ImageView imageView = (ImageView) findViewById(R.id.im2);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
pd.open();
pd.insert(picturePath);
pd.close();
}
}
Generally when you want to save your image in your database then it has many ways to store it.
1) You can save your image as a imageName in database.
2) You can also save path of image into your database and when you retrieve that path from database in string after that you can decode that path generally we can do when we are fetching from gallery.
3) You can save your image as byte[] in your database and when you want to retrieve it then you can retrieve as a BLOB image and after that convert that byte[] to Bitmap and set that bitmap to your ImageView.
see you can do two things:-
If you want image should be remain in its original place then you can use its path only,and save that path to some place like sharedPreference, fileSystem,sqlite DB, or any var.
another way you can copy that image to your application file then you can use that image
if you have path of image then you can get image like as:-
private void loadImageFromStorage(String path)
{
try {
// if you want to use the same path then use this
Bitmap b = BitmapFactory.decodeFile(pathName);
ImageView img=(ImageView)findViewById(R.id.imgPicker);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
don't forget to give permission <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I have 2 imageView to import images from gallery and set on these imageViews. I basically do this by:
String mPicPath1, mPicPath2;
protected void onCreate(Bundle icicle) {
mPicPath1 = null;
mPicPath2 = null;
}
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent data){
super.onActivityResult(requestCode, resultcode, data);
switch(requestCode){
case 1:
if (data != null && resultcode == RESULT_OK)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mPicPath1 = cursor.getString(columnIndex);
cursor.close();
logoview.setBackgroundResource(0);
logoview.setImageBitmap(BitmapFactory.decodeFile(mPicPath1));
}
break;
case 2:
if (data != null && resultcode == RESULT_OK)
{
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
cursor.moveToFirst();
mPicPath2 = cursor.getString(columnIndex);
cursor.close();
qrcodeview.setBackgroundResource(0);
qrcodeview.setImageBitmap(BitmapFactory.decodeFile(mPicPath2));
}
break;
}
and i use a button onClickListener to start intent and go to SecondActivity:
save=(Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(NewCard.this, Template.class);
if (!TextUtils.isEmpty(mPicPath1)) {
intent.putExtra("picture_path1", PicPath1);
}
if (!TextUtils.isEmpty(mPicPath2)) {
intent.putExtra("picture_path2", PicPath2);
}
startActivity(intent);
}
});
And my SecondActivity to set images on 2 different imageViews:
String pre_img_path1= getIntent().getStringExtra("picture_path1");
ImageView crdlogoframe = (ImageView) findViewById(R.id.crdlogoframe);
crdlogoframe.setImageBitmap(BitmapFactory.decodeFile(pre_img_path1));
String pre_img_path2= getIntent().getStringExtra("picture_path2");
ImageView crdqrframe = (ImageView) findViewById(R.id.crdqrframe);
crdqrframe.setImageBitmap(BitmapFactory.decodeFile(pre_img_path2));
So my problem is about the file size or resolution of the images. If i take 2 high resolution images from gallery (taken by standard camera: 1992kb, 3264x2448) and i click my save (save.onClickListener) button, i receive Force Close error. If i take small size images there is no problem(74kb, 800x600) i can proceed SecondActivity and see images are set. How i can solve this issue. Should i use a syntax to resize the images when i pick or set. The formats are both .Jpeg. Thank you very much.
i do not have the rep to comment yet so .... but as Simon said your images are to large 31MB need to try and keep things under about 16MB so you will have to re-size them before you can display them
Instead of
BitmapFactory.decodeFile(mPicPath2)
You need to use something like
BitmapFactory.decodeFile(mPicPath2, options)
Where options is an instance of BitmapFactory.Options with an inSampleSize set to something like 4 that will scale down the image as it is loaded.
I am using a very simple code to pick image from gallery, it work on my phone.
but testing it on three to four phones(Galaxy S3,Tablet etc..) it does not work.
Environment It Works:
if the image size i took or was in gallery below 500kb then it works
Environment It Does'nt Work:
if the image size i took or was in gallery above 500kb then it works
ImageView myimg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Toast.makeText(this, UUID.randomUUID().toString(),
// Toast.LENGTH_LONG).show();
myimg = (ImageView) findViewById(R.id.imageView1);
mybutton = (Button) findViewById(R.id.myButton);
mybutton.setOnClickListener(this);
}
public void onClick(View v) {
if (v == mybutton) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file path of
// selected
// image
cursor.close();
// Convert file path into bitmap image using below line.
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
// put bitmapimage in your imageview
myimg.setImageBitmap(yourSelectedImage);
}
}
}
Any one put some light on it how to handle this situation?
Any help would be appreciated.
MY SOLUTION: Ok some good answers. This is what I came up with. Not sure to answer my own question or put it here for proper stackoverflowness so if anyone knows please share.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case cameraData:
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setVisibility(View.VISIBLE);
break;
case SELECT_PICTURE:
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
File imgFile = new File(selectedImagePath);
bmp = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
break;
}
iv.setVisibility(View.VISIBLE);
iv.setImageBitmap(bmp);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, stream); // compress
byte[] ba = stream.toByteArray();
image_str = Base64.encodeBytes(ba);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
OK I have a path to picture in my gallery. I want to take that picture and turn it into a bundle so I can 64 encode it to upload to my server. here is my onActivityResult. I have it working from taking a picture with the camera just not getting it from the gallery.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case cameraData:
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
Log.e("picture","Take Picture");
break;
case SELECT_PICTURE:
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Log.e("picture",selectedImagePath);
File imgFile = new File(selectedImagePath);
bmp = (Bitmap) BitmapFactory.decodeFile(imgFile.getAbsolutePath());
Bundle extras1 = ((Cursor) imgFile).getExtras();
// bmp = (Bitmap) extras1.get("data");
Log.e("picture","from Gallery");
break;
}
}
}
the base 64 code is not mine its from this site: http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/
getPath:
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
Why would you want to turn the bitmap into a bundle? And why do you want to turn the file into a base64 String before you upload?
Here and here are examples that upload a file.
http://pastebin.com/3A5gMFsF
Seems to do what you want. Looks like when you get a file URI back you need to dig through some Content Resolvers to actually get the file itself.
Uri photoUri = data.getData();
if (photoUri != null)
{
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
bMap_image = BitmapFactory.decodeFile(filePath);
ImageView img = (ImageView) findViewById(R.id.gallery1);
img.setImageBitmap(bMap_image);
Edit: The only difference I see between this version and your version is that this version doesn't convert the filePath into a File before calling BitMap.Decode. It calls BitmapFactory.decodeFile directly on the file path returned from the content resolover.
You can directly convert the bitmap to base64.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
byte[] dataToUpload = Base64.encode(bitmapdata , DEFAULT);
To convert the bitmap to Bundle use bundle.putParcelable("dataToUpload", bitmap)
and retireve it using bundle.getParcelable("dataToUpload").