I developed an app in which the user can capture an image either from camera or gallery. For that, the user can click on the imageview, then a dialog shows up and the user can choose to capture from camera or gallery.
If the user chooses to capture the image from gallery or with the front camera then it works fine and the captured image shows up in the imageview. But if the user chooses the back camera and takes the photo and return back to activity, then the image does not show up in the imageview at all.
Here my full source code:
public class PostActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.post);
image = (ImageView) findViewById(R.id.image);
ab = getActionBar();
ab.setDisplayHomeAsUpEnabled(true);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
show(); //here the dialog box is called, to choose the capture option
}
});
image.setTag(null);
captureImageInitialization();
}
private void show() {
dialog.show();
}
private void captureImageInitialization() {
final Item[] items = {
new Item("Camera", R.drawable.ic_action_camera_dark),
new Item("Gallery", R.drawable.ic_action_collection),
};
ListAdapter adapter = new ArrayAdapter<Item>(this,
android.R.layout.select_dialog_item, android.R.id.text1, items) {
public View getView(int position, View convertView, ViewGroup parent) {
// User super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = (TextView) v.findViewById(android.R.id.text1);
// Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(
items[position].icon, 0, 0, 0);
// Add margin between image and text (support various screen
// densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp5);
return v;
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Take Image from ...");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(
"android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, PICK_FROM_CAMERA);
} else {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_FROM_FILE);
}
}
});
dialog = builder.create();
}
public static class Item {
public final String text;
public final int icon;
public Item(String text, Integer icon) {
this.text = text;
this.icon = icon;
}
#Override
public String toString() {
return text;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FROM_CAMERA:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
BitmapFactory.Options options0 = new BitmapFactory.Options();
options0.inSampleSize = 2;
options0.inScaled = false;
options0.inDither = false;
options0.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeFile(imagepath, options0);
Matrix matrix = new Matrix();
ExifInterface exif;
int m = 0;
try {
exif = new ExifInterface(imagepath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
Log.d("EXIF", "Exif: " + orientation);
if (orientation == 6) {
m = 90;
} else if (orientation == 3) {
m = 180;
} else if (orientation == 8) {
m = 270;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
matrix.postRotate(m);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), matrix, false);
ByteArrayOutputStream baos0 = new ByteArrayOutputStream();
image.setImageBitmap(getRoundedCornerBitmap(bmp));
image.setTag("1");
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos0);
byte[] imageBytes0 = baos0.toByteArray();
krt1 = Base64.encodeToString(imageBytes0, Base64.DEFAULT);
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
imagepath = getPath(mImageCaptureUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inScaled = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeFile(imagepath, options);
ExifInterface exif2;
int m2 = 0;
try {
exif2 = new ExifInterface(imagepath);
int orientation = exif2.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
Log.d("EXIF", "Exif: " + orientation);
if (orientation == 6) {
m2 = 90;
} else if (orientation == 3) {
m2 = 180;
} else if (orientation == 8) {
m2 = 270;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
Matrix matrix2 = new Matrix();
matrix2.postRotate(m2);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), matrix2, false);
image.setImageBitmap(getRoundedCornerBitmap(bmp));
image.setTag("1");
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos2);
byte[] imageBytes2 = baos2.toByteArray();
krt1 = Base64.encodeToString(imageBytes2, Base64.DEFAULT);
break;
}
}
public String getPath(Uri uri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getApplicationContext().getContentResolver().query(uri,
proj, null, null, null);
if (cursor.moveToFirst()) {
;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
This issue with the back camera is really weird, because I never had such an issue. (BTW tested on Samsung device). Any help is appreciated.
I am using this code for taking the image from front facing camera -
public class CameraController {
private Context context;
private boolean hasCamera;
private Camera camera;
private int cameraId;
public CameraController(Context c){
context = c.getApplicationContext();
if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
cameraId = getFrontCameraId();
if(cameraId != -1){
hasCamera = true;
}else{
hasCamera = false;
}
}else{
hasCamera = false;
}
}
public boolean hasCamera(){
return hasCamera;
}
public void getCameraInstance(){
camera = null;
if(hasCamera){
try{
camera = Camera.open(cameraId);
prepareCamera();
}
catch(Exception e){
hasCamera = false;
}
}
}
public void takePicture(){
if(hasCamera){
camera.takePicture(null,null,mPicture);
}
}
public void releaseCamera(){
if(camera != null){
camera.stopPreview();
camera.release();
camera = null;
}
}
private int getFrontCameraId(){
int camId = -1;
int numberOfCameras = Camera.getNumberOfCameras();
CameraInfo ci = new CameraInfo();
for(int i = 0;i < numberOfCameras;i++){
Camera.getCameraInfo(i,ci);
if(ci.facing == CameraInfo.CAMERA_FACING_FRONT){
camId = i;
}
}
return camId;
}
private void prepareCamera(){
SurfaceView view = new SurfaceView(context);
try{
camera.setPreviewDisplay(view.getHolder());
}catch(IOException e){
throw new RuntimeException(e);
}
camera.startPreview();
Camera.Parameters params = camera.getParameters();
params.setJpegQuality(100);
camera.setParameters(params);
}
private PictureCallback mPicture = new PictureCallback(){
#Override
public void onPictureTaken(byte[] data, Camera camera){
File pictureFile = getOutputMediaFile();
if(pictureFile == null){
Log.d("TEST", "Error creating media file, check storage permissions");
return;
}
try{
Log.d("TEST","File created");
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
}catch(FileNotFoundException e){
Log.d("TEST","File not found: "+e.getMessage());
} catch (IOException e){
Log.d("TEST","Error accessing file: "+e.getMessage());
}
}
};
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if(!mediaStorageDir.exists()){
if(!mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath()+File.separator+"IMG_"+timeStamp+".jpg");
return mediaFile;
}
}
Hope this helps you.
Related
I am trying to develop some kind of OCR application with Text Recognizing feature. I wrote and found some codes which is working properly but my problem is I want make some customization in the camera layout. I want to add my own capture button and add a frame. I actually did it on a different project with "surface view/holder". But I cannot implement my project because it works so differently.
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_GALLERY = 0;
private static final int REQUEST_CAMERA = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private Uri imageUri;
private TextView detectedTextView; // layouttaki text view
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.choose_from_gallery).setOnClickListener(new View.OnClickListener() { // galeriden resim seçme işlemi
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, REQUEST_GALLERY);
}
});
findViewById(R.id.take_a_photo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // resim çekme işlemi
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
});
detectedTextView = (TextView) findViewById(R.id.detected_text);
detectedTextView.setMovementMethod(new ScrollingMovementMethod());
}
private void inspectFromBitmap(Bitmap bitmap) { //kendisine gelen bitmap resimden inspect yapar
TextRecognizer textRecognizer = new TextRecognizer.Builder(this).build();
try {
if (!textRecognizer.isOperational()) {
new AlertDialog.
Builder(this).
setMessage("Text recognizer could not be set up on your device").show();
return;
}
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> origTextBlocks = textRecognizer.detect(frame);
List<TextBlock> textBlocks = new ArrayList<>();
for (int i = 0; i < origTextBlocks.size(); i++) {
TextBlock textBlock = origTextBlocks.valueAt(i);
textBlocks.add(textBlock);
}
Collections.sort(textBlocks, new Comparator<TextBlock>() {
#Override
public int compare(TextBlock o1, TextBlock o2) {
int diffOfTops = o1.getBoundingBox().top - o2.getBoundingBox().top;
int diffOfLefts = o1.getBoundingBox().left - o2.getBoundingBox().left;
if (diffOfTops != 0) {
return diffOfTops;
}
return diffOfLefts;
}
});
StringBuilder detectedText = new StringBuilder();
for (TextBlock textBlock : textBlocks) {
if (textBlock != null && textBlock.getValue() != null) {
detectedText.append(textBlock.getValue());
detectedText.append("\n");
}
}
detectedTextView.setText(detectedText); // detectedText is a final string
}
finally {
textRecognizer.release();
}
}
private void inspect(Uri uri) {
InputStream is = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 2;
options.inScreenDensity = DisplayMetrics.DENSITY_LOW;
bitmap = BitmapFactory.decodeStream(is, null, options);
Bitmap rotatedMap = RotateBitmap(bitmap,90);
inspectFromBitmap(rotatedMap);
} catch (FileNotFoundException e) {
Log.w(TAG, "Failed to find the file: " + uri, e);
} finally {
if (bitmap != null) {
bitmap.recycle();
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
Log.w(TAG, "Failed to close InputStream", e);
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_GALLERY:
if (resultCode == RESULT_OK) {
inspect(data.getData());
}
break;
case REQUEST_CAMERA:
if (resultCode == RESULT_OK) {
if (imageUri != null) {
inspect(imageUri);
}
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
public static Bitmap RotateBitmap(Bitmap source, float angle) // it rotates the bitmap for given parameter
{
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
In that case, what should I do ? Thank you guys.
No, you cannot change the layout of the camera app that fulfills ACTION_IMAGE_CAPTURE intent. Actually, different devices will not have same camera apps. Each may have very different look-and-feel. You need a 'custom camera' to control its layout and UX.
i am building a app in which user can capture image from camera and then edit that image and store / display the image in a gridview.the problem i am facing is that when the user capture the image instead of crop the image it directly display it in gridview . i need help in this thanks in advance
this is my code
public class MainActivity extends Activity implements OnClickListener {
Button captureBtn = null;
final int CAMERA_CAPTURE = 1;
private Uri picUri;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private GridView grid;
private List<String> listOfImagesPath;
Intent CropIntent;
public static final String GridViewDemo_ImagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GridViewDemo/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
captureBtn = (Button)findViewById(R.id.capture_btn1);
captureBtn.setOnClickListener(this);
grid = ( GridView) findViewById(R.id.gridviewimg);
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
}
public void ImageCropFunction() {
// Image Crop Code
try {
CropIntent = new Intent("com.android.camera.action.CROP");
CropIntent.setDataAndType(picUri, "image/*");
CropIntent.putExtra("crop", "true");
CropIntent.putExtra("outputX", 180);
CropIntent.putExtra("outputY", 180);
CropIntent.putExtra("aspectX", 3);
CropIntent.putExtra("aspectY", 4);
CropIntent.putExtra("scaleUpIfNeeded", true);
CropIntent.putExtra("return-data", true);
startActivityForResult(CropIntent, 1);
} catch (ActivityNotFoundException e) {
}
}
//Image Crop Code End Here
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0.getId() == R.id.capture_btn1) {
try {
//use standard intent to capture an image
Intent captureIntent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch(ActivityNotFoundException anfe){
//display an error message
String errorMessage = "Whoops - your device doesn't support
capturing images!";
Toast toast = Toast.makeText(this, errorMessage,
Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
//user is returning from capturing an image using the camera
if(requestCode == CAMERA_CAPTURE){
ImageCropFunction();
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
String imgcurTime = dateFormat.format(new Date());
File imageDirectory = new File(GridViewDemo_ImagePath);
imageDirectory.mkdirs();
String _path = GridViewDemo_ImagePath + imgcurTime+".jpg";
try {
FileOutputStream out = new FileOutputStream(_path);
thePic.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (FileNotFoundException e) {
e.getMessage();
} catch (IOException e) {
e.printStackTrace();
}
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
}
}
}
private List<String> RetriveCapturedImagePath() {
List<String> tFileList = new ArrayList<String>();
File f = new File(GridViewDemo_ImagePath);
if (f.exists()) {
File[] files=f.listFiles();
Arrays.sort(files);
for(int i=0; i<files.length; i++){
File file = files[i];
if(file.isDirectory())
continue;
tFileList.add(file.getPath());
}
}
return tFileList;
}
public class ImageListAdapter extends BaseAdapter
{
private Context context;
private List<String> imgPic;
public ImageListAdapter(Context c, List<String> thePic)
{
context = c;
imgPic = thePic;
}
public int getCount() {
if(imgPic != null)
return imgPic.size();
else
return 0;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
BitmapFactory.Options bfOptions=new BitmapFactory.Options();
bfOptions.inDither=false; //Disable Dithering mode
bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage=new byte[32 * 1024];
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
FileInputStream fs = null;
Bitmap bm;
try {
fs = new FileInputStream(new File(imgPic.get(position).toString()));
if(fs!=null) {
bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
imageView.setImageBitmap(bm);
imageView.setId(position);
imageView.setLayoutParams(new GridView.LayoutParams(200, 160));
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fs!=null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageView;
}
}
}
Let me know if it works
first of all change
startActivityForResult(CropIntent, 1);
to
`startActivityForResult(CropIntent, 2);`
and add to onActivityResult add this:
picUri = Uri.parse(_path);
after that in your onActivityResult remove
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
and add new result like
if(requestCode == CAMERA_CAPTURE){
....
} else if(requestCode == 2){
..
}
and last step in your new statement add this line:
else if(requestCode == 2){
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
}
https://github.com/ArthurHub/Android-Image-Cropper
Use this library. It's very easy to use
I am creating an android app in which the user can click the images which would be shown in grid view once the image is captured this part works fine but the quality of the image is very low and even if i take the image from the high resolution camera it shows the width and height of the image as 160 and 200 px respectively.
I would like to know is there any way to capture the image in original size than compress the image what we do in whatsapp. since i am a newbie to android i don't know what i have to do.
public class CamAct extends Activity implements OnClickListener {
Button captureBtn = null;
final int CAMERA_CAPTURE = 1;
private Uri picUri;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private GridView grid;
private List<String> listOfImagesPath;
public static final String GridViewDemo_ImagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GridViewDemo/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camlayout);
captureBtn = (Button)findViewById(R.id.capture_btn1);
captureBtn.setOnClickListener(this);
grid = ( GridView) findViewById(R.id.gridviewimg);
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
}
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.capture_btn1) {
try {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(captureIntent, CAMERA_CAPTURE);
} catch(ActivityNotFoundException anfe){
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CAMERA_CAPTURE){
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
String imgcurTime = dateFormat.format(new Date());
File imageDirectory = new File(GridViewDemo_ImagePath);
imageDirectory.mkdirs();
String _path = GridViewDemo_ImagePath + imgcurTime+".jpg";
try {
FileOutputStream out = new FileOutputStream(_path);
thePic.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (FileNotFoundException e) {
e.getMessage();
} catch (IOException e) {
e.printStackTrace();
}
listOfImagesPath = null;
listOfImagesPath = RetriveCapturedImagePath();
if(listOfImagesPath!=null){
grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
}
}
}
}
private List<String> RetriveCapturedImagePath() {
List<String> tFileList = new ArrayList<String>();
File f = new File(GridViewDemo_ImagePath);
if (f.exists()) {
File[] files=f.listFiles();
Arrays.sort(files);
for(int i=0; i<files.length; i++){
File file = files[i];
if(file.isDirectory())
continue;
tFileList.add(file.getPath());
}
}
return tFileList;
}
ImageAdapter:
public class ImageListAdapter extends BaseAdapter
{
private Context context;
private List<String> imgPic;
public ImageListAdapter(Context c, List<String> thePic)
{
context = c;
imgPic = thePic;
}
public int getCount() {
if(imgPic != null)
return imgPic.size();
else
return 0;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
BitmapFactory.Options bfOptions=new BitmapFactory.Options();
bfOptions.inDither=false; //Disable Dithering mode
bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage=new byte[16 * 1024];
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
FileInputStream fs = null;
Bitmap bm;
try {
fs = new FileInputStream(new File(imgPic.get(position).toString()));
if(fs!=null) {
bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
imageView.setImageBitmap(bm);
imageView.setId(position);
imageView.setLayoutParams(new GridView.LayoutParams(200, 160));
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fs!=null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageView;
}
}
Try this:
captureBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(subname.getText().toString().isEmpty()){
Snackbar.make(view, "Select Subject", Snackbar.LENGTH_LONG).show();
}else {
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
ImagefileUri = Uri.fromFile(getFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, ImagefileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(requestCode == CAMERA_PIC_REQUEST){
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int dw = size.x;
int dh = size.y;
// Load up the image's dimensions not the image itself
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
/ (float) dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
/ (float) dw);
Log.v("HEIGHTRATIO", "" + heightRatio);
Log.v("WIDTHRATIO", "" + widthRatio);
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
// Height ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
// Width ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeFile(ImagefileUri.getPath(),
bmpFactoryOptions);
InitilizeGridLayout();
// loading all image paths from SD card
imagePaths = utils.getFilePaths();
// Gridview adapter
adapter = new GridViewImageAdapter(Cam.this, imagePaths,
columnWidth);
// setting grid view adapter
gridView.setAdapter(adapter);
}
}else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
It will capture the image as per the camera width and height so you will get the image in good quality as well as the image adapter you are using has an temp storage which can store only 5 or 6 images of high quality so change the grid view .To know more about displaying images from sdcard to gridview use the following link: Loading images from sdcard and display it in gridview
Hope this code helps you:)
I have written a program which has a button which when clicked captures a photo through camera and want to set the captured image on the same activity below the button.
Everything works without giving an error. The image is also getting saved to the respective location. But the image is not getting displayed, which means something is going wrong.
Below is my Code for the above :
public class MainActivity extends ActionBarActivity {
Button b1;
private File imageFile;
ImageView img;
private Uri uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.buttonPicture);
img = (ImageView) findViewById(R.id.imageView1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageFile = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"test.jpeg");
uri = Uri.fromFile(imageFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 0 && data != null) {
switch (resultCode) {
case Activity.RESULT_OK:
if (imageFile.exists()) {
Bitmap photo = (Bitmap) data.getExtras().get(
MediaStore.EXTRA_OUTPUT);
previewCapturedImage();
img.setImageBitmap(photo);
} else {
Toast.makeText(getBaseContext(), "File was not saved",
Toast.LENGTH_SHORT).show();
}
break;
case Activity.RESULT_CANCELED:
break;
default:
break;
}
}
}
private void previewCapturedImage() {
try {
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath(),
options);
img.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
Once you press Ok button after capturing image, you can take the captured image from the Extras using Intent(data in your case) parameter received through onActivityResult
Simply use this code inside onActivityResult
Bitmap photo = (Bitmap) data.getExtras().get("data");
imgViewLogo.setImageBitmap(photo);
Try with below code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == 0 && data != null) {
switch (resultCode) {
case Activity.RESULT_OK:
if (imageFile.exists()) {
private String selectedImagePath;
Uri selectedImageUri = data.getData();
String filePath = null;
String filemanagerstring = selectedImageUri.getPath();
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getApplicationContext(), R.string.unknownPath, Toast.LENGTH_LONG).show();
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} else {
Toast.makeText(getBaseContext(), "File was not saved",
Toast.LENGTH_SHORT).show();
}
break;
case Activity.RESULT_CANCELED:
break;
default:
break;
}
}
}
//getPath method
public String getPath(Uri uri) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
//decodeFile method
public void decodeFile(String filePath) {
private Bitmap bitmap;
try {
File f = new File(filePath);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
bitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
ByteArrayOutputStream outstudentstreamOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outstudentstreamOutputStream);
img.setImageBitmap(selfieBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I have been stuck in camera for 6 days but not getting any proper solution. When I am capturing image through camera intent, image is being rotated. I tried to fix the orientation but sometimes it's not giving bitmap value in onActivityResult(). It shows a black screen when I try to set image in ImageView. Here is my code Please help me -
//call intent to capture image
captureBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
{
startActivityForResult(takePictureIntent,AlletConstants.CAPTURE_RECEIPT_IMAGE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case AlletConstants.CAPTURE_RECEIPT_IMAGE:
if(data != null)
{
Uri qrcodeImageUri = data.getData();
bitmapReceiptImage = handleQrBarCodeImage(qrcodeImageUri);
mImageCaptureUri = AlletCommonUtility.bitmapToUri(getActivity(), bitmapReceiptImage);
doCrop();
AlletCommonUtility.showToast(getActivity(),"Uri = "+mImageCaptureUri);
}
break;
case AlletConstants.CROP_RECEIPT_FROM_CAMERA:
if(data != null)
{
Bundle qrcodeextras = data.getExtras();
if (qrcodeextras != null) {
Bitmap cropBitmap = qrcodeextras.getParcelable("data");
receiptImageView.setImageBitmap(cropBitmap);
bitmapReceiptImage = cropBitmap;
}
File qrcodeFile = new File(mImageCaptureUri.getPath());
if (qrcodeFile.exists())
qrcodeFile.delete();
}
break;
default:
break;
}
}
// use to get bitmap from uri
private Bitmap handleReceiptImage(Uri selectedImageUri)
{
String[] filePathColumn = {MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = setCameraImageRotation(picturePath);
return bitmap;
}
private Bitmap setCameraImageRotation(String picturePath)
{
Bitmap bitmapQrBarImage = null;
try {
File f = new File(picturePath);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
AlletCommonUtility.showToast(getActivity(), "Orienattion = "+orientation);
Matrix mat = new Matrix();
mat.postRotate(getImageOrientation(orientation));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize= 4;
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, options);
bitmapQrBarImage = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
if (bitmapQrBarImage != null) {
AlletCommonUtility.showToast(getActivity(), "CAMERA_PIC_SELECTION = "+bitmapQrBarImage);
}
}
catch (IOException e) {
Log.w("TAG", "-- Error in setting image");
}
catch(OutOfMemoryError oom) {
Log.w("TAG", "-- OOM Error in setting image");
}
return bitmapQrBarImage;
}
// Use to crop image
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
AlletCommonUtility.showToast(getActivity(), AlletMessage.NOT_CROP_IMAGE);
return;
} else {
intent.setData(mImageCaptureUri);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, AlletConstants.CROP_RECEIPT_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getActivity().getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = getActivity().getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent= new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(getActivity(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose Crop App");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
startActivityForResult( cropOptions.get(item).appIntent, AlletConstants.CROP_RECEIPT_FROM_CAMERA);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
#Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
getActivity().getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
// use to rotate captured image from device camera
public static int getImageOrientation(int rotation)
{
int angle = 0;
switch (rotation) {
case 0:
angle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
angle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
angle = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
angle = 270;
break;
default:
break;
}
return angle;
}
I am getting image in landscape mode but not in potrait mode. Camera preview automatically rotates by 90 degrees after capturing image.
It is because of the image's EXIF data. You need to use a rotation method.
Depending on your build-in Camera orientation and orientation of device the pictures will have different rotations. You check the rotation of your particular image through ExifInterface.
/**
* #param filename Path to image file
* #param captureTime Time when image file was created
*/
public static int extractExifOrientationTagFromImageFile(String filename, long creationTime) {
/* The issue is on some devices, there's a bug that makes the picture taken saved in your app folder without proper
exif tags while a properly rotated image is saved in the android default folder (even though it shouldn't be).
Now what we do is recording the time when we're starting the camera app. Then we query
the Media Provider to see if any pictures were saved after this timestamp we've saved. That means most likely Android OS
saved the properly rotated picture in the default folder and of course put an entry in the media store and we can use the
rotation information from this row. */
int imageRotation = -1;
long imageFileSize = new File(filename).length();
Cursor mediaFileCursor = getContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION, MediaStore.MediaColumns.SIZE },
MediaStore.MediaColumns.DATE_ADDED + " >= ?", new String[] { String.valueOf(creationTime / 1000 - 1) },
MediaStore.MediaColumns.DATE_ADDED + " DESC");
if((mediaFileCursor != null) && (mediaFileCursor.getCount() != 0)) {
while(mediaFileCursor.moveToNext()) {
long mediaFileSize = getLongFromCursor(mediaFileCursor, MediaStore.MediaColumns.SIZE);
// Extra check to make sure that we are getting the orientation from the proper file
if(mediaFileSize == imageFileSize) {
imageRotation = getIntFromCursor(mediaFileCursor, MediaStore.Images.ImageColumns.ORIENTATION);
break;
}
}
}
/* Now if the rotation at this point is still -1, then that means this is one of the devices with proper rotation information. */
if(imageRotation == -1) {
ExifInterface exif = null;
try {
exif = new ExifInterface(filename);
}
catch (IOException e) {
e.printStackTrace();
}
imageRotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
}
return imageRotation;
}
private static final int COLUMN_NOT_EXISTS = -1;
public static Long getLongFromCursor(Cursor cursor, String columnName) {
int columnIndex;
if((columnIndex = cursor.getColumnIndex(columnName)) != COLUMN_NOT_EXISTS) {
return cursor.getLong(columnIndex);
}
else {
return null;
}
}
public static Integer getIntFromCursor(Cursor cursor, String columnName) {
int columnIndex;
if((columnIndex = cursor.getColumnIndex(columnName)) != COLUMN_NOT_EXISTS) {
return cursor.getInt(columnIndex);
}
else {
return null;
}
}
Now when you have your image rotation you can rotate it's bitmap properly:
int imageRotation = extractExifOrientationTagFromImageFile(lastCapturedMediaUriPath, cameraAppInvokeTime);
Matrix matrix = new Matrix();
switch(imageRotation) {
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.postRotate(90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.postRotate(180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.postRotate(270);
break;
default:
break;
}
final Bitmap loadedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);