Android: How do i display this image into a bitmap? - android

What i'm doing/trying to do, is.
1. Take a photo
2. Save it
3. Load/display it into a Bitmap
Opening the Built in camera application:
public void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory()+ File.separator + "image.jpg");
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//Check that request code matches ours:
if (requestCode == REQUEST_IMAGE_CAPTURE){
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
}
}
decodeSamoleBitmapFromFile:
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
I was hoping for it to load it into a bitmap. If anyone could point me in the right direction that would be very helpful!

In order to display a Bitmap, you'll have to use an ImageView. Once you have both the bitmap and the reference to your ImageView, call ImageView.setImageBitmap(Bitmap) to display your bitmap.

Related

How to resize the picture taken on Android?

I want to send a picture I took to server with multipart/form-data.
Of course, all the process goes very well.
I get the absolute path of the picture on onActivityResult. I sent it to AsyncTask class to change it into File object. Then, I use FileInputStream to send the picture to server.
Here's my code for sending picture.
MainActivity:
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(resultCode != RESULT_OK)
return;
if(requestCode == PICK_FROM_CAMERA){
// uri of selected picture
imageUri = data.getData();
// path of selected picture
Cursor c = this.getContentResolver().query(imageUri, null, null, null, null);
c.moveToNext();
absolutePath = c.getString(c.getColumnIndex(MediaStore.MediaColumns.DATA));
Glide.with(this).load(imageUri).into(image);
}
}
Asynctask class:
absolutePath is in params[7]
FileInputStream fileInputStream ;
wr.writeBytes("\r\n--" + boundary + "\r\n");
wr.writeBytes("Content-Disposition: form-data; name=\"file1[]\"; " +
"filename=\"image.jpg\"\r\n");
wr.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
fileInputStream = new FileInputStream(params[7]);
When I send the picture, I just send it without resizing.
It takes too much time and data to finish sending.
I want to make the picture smaller when sending to server.
that is, with absolute Path, I want to make smaller picture that can be turned into File object.
Can anyone give me some hint?
You can store your imageFile as Uri variable and then resize your image according to your desired width and height to be compressed.
Bitmap b = BitmapFactory.decodeFile(String.valueOf(fileUri));
Bitmap out = Bitmap.createScaledBitmap(b, IMG_WIDTH, IMG_HEIGHT, false);
FileOutputStream fOut;
try {
fOut = new FileOutputStream(fileUri);
out.compress(Bitmap.CompressFormat.JPEG, 60, fOut);
fOut.flush();
fOut.close();
b.recycle();
out.recycle();
Log.i("Compressing file", String.valueOf(uriFile));
} catch (Exception e) {
Log.e("ErrInCompressingPicture","" + e);
}
You can compress the picture you got before you send to server!
one solution is set inSampleSize directly:
public static Bitmap getImage(String imgPath){
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2;
try {
b=BitmapFactory.decodeFile(imgPath, options);
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
the other solution is set width and height of you want:
public static Bitmap getSmallBitmap(String imgPath,int reWidth,int reHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imgPath, options);
int width = options.outWidth;
int height = options.outHeight;
int inSampleSize=0;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
options.inSampleSize = inSampleSize;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(imgPath, options);
}

When I take photo it is not shown on the imageView only in Galaxy s4

In my app I have to let the user take photo from camera / choose from gallery .
My code working fine on some device but when I run on Galaxy s4 and taking photo by camera the photo doesnt show on the imageView (choose from gallery -working fine)the problem is just when take photo by camera in Galaxy s4.
I scaled the picture before display it on the imageView.
Here is my code to take the picture:
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
this is my code after take photo:
if (requestCode == 1)
{
File f = new File(Environment.getExternalStorageDirectory().toString());
File image_file = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles())
{
if (temp.getName().equals("temp.jpg"))
{
f = temp;
break;
}
}
try
{
Bitmap bitmap;
//BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
//bitmap=decodeFile(f.getAbsolutePath());//Collapse image
//setImageOnBitmap(bitmap);//Set the image on the imageview
BitmapHandler b=new BitmapHandler(getApplicationContext());
bitmap=b.decodeFileAsPath(f.getAbsolutePath(),"camera");
setImageOnBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
}
catch (Exception e)
{
e.printStackTrace();
}
}
this is my function to decode the file of the image:
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
I have a similar issue on S4, and this is what solved for me:
mImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
Hope this helps.

unable to add image to imageview from camera capture

I am developing one application in which I have to capture image from camera and add to ImageView. Here I have a problem while showing image on ImageView. If I click save button the image is not showing on ImageView for the first time,but for second time it is showing,please solve my problem, I am unable to find solution for this.
Code Snippet:
fromCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* Log.e("OPEN", "CAMERA");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, RESUL_CameraT_LOAD_IMAGE);*/
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(Environment.getExternalStorageDirectory()+File.separator +
"fav.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, RESUL_CameraT_LOAD_IMAGE);
uploadalertDialog.dismiss();
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = null;
Bitmap bitmap;
try {
switch (requestCode) {
case RESUL_CameraT_LOAD_IMAGE:
if (resultCode == Activity.RESULT_OK) {
// imageView.setImageResource(android.R.color.transparent);
Log.e("GET IMAGE", "PATH");
try{
File file = new File(Environment.getExternalStorageDirectory()+File.separator
+ "fav.jpg");
bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 300, 300);
uloadImgView.setImageBitmap(bitmap);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90,
byteArray);
byte[] byte_arr = byteArray.toByteArray();
base64 = Base64.encodeToString(byte_arr, Base64.DEFAULT);
}
catch(Exception e){
e.printStackTrace();
}
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
First of all add the following permission in you app's manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Then check the following code which I used in my application to set s user's profile pic.
// on click listener for the camera trigger
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraintent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraintent, 101);
}
});
//onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImage = null;
Bitmap bitmap;
try {
switch (requestCode) {
case 101:
if (resultCode == Activity.RESULT_OK) {
if (null != data) {
selectedImage = data.getData(); // the uri of the image
// taken
bitmap = decodeSampledBitmapFromUri(this,
selectedImage, 100, 100);
image.setImageBitmap(bitmap);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
//Bitmap sampling
public static Bitmap decodeSampledBitmapFromUri(Activity callingActivity,
Uri uri, int reqWidth, int reqHeight) {
try {
InputStream input = callingActivity.getContentResolver()
.openInputStream(uri);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 2; // make the bitmap size half of the
// original one
BitmapFactory.decodeStream(input, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
input.close();
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
input = callingActivity.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
return bitmap;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
//calculate sample size
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}

Take picture then load in ImageView not always working

I'm using code the from the examples here.
My issue is that sometimes the image doesn't load into the ImageView. I've just noticed this behavior recently. I've found that if I debug through the code it works 100% of the time.
My assumption is that the image file sometimes doesn't get created in time to be usable in the onActivityResult. Has anyone run into this issue? Suggestions on how to compensate?
May be it is mobile processing speed issue! can't tell exactly but i Tried it in this way, and it work like charm always!
public class LaunchCamera extends Activity {
ImageView imVCature_pic;
Button btnCapture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch_camera);
initializeControls();
}
private void initializeControls() {
imVCature_pic=(ImageView)findViewById(R.id.imVCature_pic);
btnCapture=(Button)findViewById(R.id.btnCapture);
btnCapture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/* create an instance of intent
* pass action android.media.action.IMAGE_CAPTURE
* as argument to launch camera
*/
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
/*create instance of File with name img.jpg*/
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
/*put uri as extra in intent object*/
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
/*start activity for result pass intent as argument and request code */
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//if request code is same we pass as argument in startActivityForResult
if(requestCode==1){
//create instance of File with same name we created before to get image from storage
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
//get bitmap from path with size of
imVCature_pic.setImageBitmap(decodeSampledBitmapFromFile(file.getAbsolutePath(), 600, 450));
}
}
public static Bitmap decodeSampledBitmapFromFile(String path,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
//Query bitmap without allocating memory
options.inJustDecodeBounds = true;
//decode file from path
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
//decode according to configuration or according best match
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight) {
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth) {
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
//if value is greater than 1,sub sample the original image
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
}
I have taken reference from this and this.

How to get an Image of specific dimensions from native camera

This is the code I am using to get a full sized image, which is >2mb in size and 3560 X 1876 in dimension.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image = (ImageView) findViewById(R.id.image);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
filePath = Environment.getExternalStorageDirectory() + "/Full_"
+ System.currentTimeMillis() + ".jpeg";
File file = new File(filePath);
Uri output = Uri.fromFile(file);
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, output);
startActivityForResult(i, CAPTURE_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap photo = BitmapFactory.decodeFile(filePath, options);
image.setImageBitmap(photo);
}
Is there a way to get the image of specific size, in my case a <100kb sized image of dimensions 480 x 320.
You can take a look at this blog post I wrote on how to get Images from device's camera Activity:
Guide: Android: Use Camera Activity for Thumbnail and Full Size Image
If you look at the end of the guide, you have this method:
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
you can provider there the required dimensions for your image output.
you have to use the inSampleSize from BitmapFactory.Options. Through it the decoder will downsample your image of the inSampleSize. For instance inSampleSize = 2 will create a bitmap of width/2 and heigth/2
int destWidth = 480;
int destHeight = 320;
while ( (bitmapWidth/2 > destWidth)
|| (bitmapHeight/2 > destHeight)) {
++inSampleSize;
bitmapWidth /= 2;
bitmapHeight /=2;
}
What if using a simplest way to do it. Copy this method, pass your bitmap and required height and width, get a scaled image back :)
public static Bitmap resizeBitmap(Bitmap originalBitmap, int width, int height) {
float scaleWidth = ((float) width) / originalBitmap.getWidth();
float scaleHeight = ((float) height) / originalBitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(originalBitmap, 0, 0, original.getWidth(),original.getHeight(), matrix, true);
}

Categories

Resources