Create folder and store Image by camera - java

please read my code ask solution how to create folder
public class CameraActivity extends ActionBarActivity {
private static final int ACTION_TAKE_IMAGE = 1;
Button btnImage;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
imageView = (ImageView)findViewById(R.id.imageView);
btnImage= (Button) findViewById(R.id.buttonCapture);
btnImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takeVideoIntent, ACTION_TAKE_IMAGE);
}
});
}
#onActivityResult start
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK)
{
try
{
AssetFileDescriptor imageAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r");
FileInputStream fis = imageAsset.createInputStream();
File root=new File(Environment.getExternalStorageDirectory(),"/Vipul/RecordImage/");
if (!root.exists()) {
System.out.println("No directory");
root.mkdirs();
}
File file;
file=new File(root,"IMG_"+System.currentTimeMillis()+".jpg" );
FileOutputStream fos = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) > 0) {
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
if(requestCode == ACTION_TAKE_IMAGE && resultCode == RESULT_OK){
Bundle bundle = data.getExtras();
Bitmap imageBitmap = (Bitmap) bundle.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
}
this code work 2.3 capture Image but work and not create folder not store in my specific folder please ask your answer

UPDATE
//declare
int num = 0;
//.....//
//*onclik button
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Create folder
File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "Myfolder");
imagesFolder.mkdirs();
//Asign name for image
File image = new File(imagesFolder, "Pic" + (num +1) + ".png");
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
//launch camera app with result code (forResult)
startActivityForResult(cameraIntent, 1);
protected void onActivityResult (int requestCode, int resultCode, Intent data)
{
if (requestCode == 1 && resultCode == RESULT_OK)
{
//create bitmap with image
Bitmap bMap = BitmapFactory.decodeFile(
Environment.getExternalStorageDirectory() +
"/Myfolder/" + "Pic" + num + ".png");
//Add bitmap to ImageView
//Show on screen
imageView.setImageBitmap(bMap);
}

To use different name for image everytime you can use method getTimeInMillis() as Calendar mCalendar = Calendar.getInstance();
String n = ""+mCalendar.getTimeInMillis();
String fname = "Pic-" + n.substring(5) + ".png";
//Asign name for image
File image = new File(imagesFolder, fname);
Uri uriSavedImage = Uri.fromFile(image);

try this code
public class CameraActivity extends ActionBarActivity {
// private static final int ACTION_TAKE_IMAGE = 1;
Button btnImage;
ImageView imageView;
File image;
String picturePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
imageView = (ImageView) findViewById(R.id.imageView);
btnImage = (Button) findViewById(R.id.buttonCapture);
btnImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Create folder
File imagesFolder = new File(
Environment.getExternalStorageDirectory(), "Vipul/image");
imagesFolder.mkdirs();
//Asign name for image
String fname = "Pic-" + System.currentTimeMillis() + ".png";
image= new File(imagesFolder, fname);
Uri uriSavedImage = Uri.fromFile(image);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
//launch camera app with result code (forResult)
startActivityForResult(cameraIntent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
picturePath=image.getAbsolutePath();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(), bitmapOptions);
imageView.setImageBitmap(bitmap);
}
}
}
final solution

Related

Save image to a new directory(app_name)

The following code is able to save images in pictures directory, but I'm not able to find the perfect way to save image files to the desired app directory using URI.
Edit: The perfect way to store image files to a new directory which can be accessed by other apps is the requirement
SaveActivity.java
final MediaManager mediaManager = new MediaManager(this);
Uri imageURI = mediaManager.GetImageUri();
final ImageView imageHolder = findViewById(R.id.imageHolder);
Glide.with(this).load(imageURI).into(imageHolder);
final String filename = mediaManager.getFileName(imageURI);
save.setOnClickListener(new View.OnClickListener() {#Override public void onClick(View v) {
imageHolder.setDrawingCacheEnabled(true);
Bitmap bitmap = imageHolder.getDrawingCache();
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, filename, "description");
}
});
MainActivity.java
ImageButton btImgSettings = findViewById(R.id.btnPhoto);
btnPhoto.setOnClickListener(new View.OnClickListener() {#Override public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
switch (requestCode){
case 1: if (uri != null) {
String stringUri = uri.toString();
Intent intent = new Intent(this, SaveActivity.class);
intent.putExtra("imageId", stringUri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
break;
default:
break;
}
}
}
MediaManager
public class MediaManager {
Activity activity;
public MediaManager(Activity activity) {
this.activity = activity;
}
public Uri GetImageUri() {
Uri imageURI = null;
Bundle bundle = activity.getIntent().getExtras();
if (bundle != null) {
String imageId = bundle.getString("imageId");
imageURI = Uri.parse(imageId);
}
return imageURI;
}
}
Thank you :)
Copy the file to your directory and then use.
Bitmap image= MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "YourDirectory");
if (!root.exists()) root.mkdirs();
String file = root.toString() + File.separator + "FileName" + ".jpg";
try {
FileOutputStream fOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fOutputStream);
image.compress(Bitmap.CompressFormat.JPEG, 100, bos);
fOutputStream.flush();
fOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(context, new String[]{file}, null, null);
//This line notifies the system that an image was added and to show it in the gallery.
Hope this helps. Feel free to ask for any clarifications.

In Android studio , in my app the image is not getting replaced with the bitmap

In Android studio , in my app the image is not getting replaced with the bitmap I create,the path is correct but the ic_action_android is not getting replaced with my fresh captured image.
In OnCreate:
btOpen.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
//Open Camera
// Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(cameraIntent.resolveActivity(getPackageManager())!=null)
{
File imageFile= null;
try{
imageFile = getImageFile();
}catch(IOException e){
Toast.makeText(getApplicationContext(), "get image file failed", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
if(imageFile != null)
{
Uri imageUri= FileProvider.getUriForFile(MainActivity.this,"com.example.android.provider",imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(cameraIntent,IMAGE_REQUEST);
}
else
{
Toast.makeText(getApplicationContext(), "Imagefile is null", Toast.LENGTH_SHORT).show();
}
}
//startActivityForResult(intent,100);
}
});
private File getImageFile()throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageName="jpg_"+timeStamp+"_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(imageName,".jpg",storageDir);
currentImagePath= imageFile.getAbsolutePath();
return imageFile;
}
The on Activity result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
ImageView imageView= new ImageView(MainActivity.this);
imageView.setImageResource(R.drawable.ic_action_android);
addView(imageView,1000,1000);
Log.i(TAG, "The image path is " + currentImagePath);
final Bitmap mBitmap= BitmapFactory.decodeFile(getIntent().getStringExtra(currentImagePath));
if (requestCode == 100) {
//Get Capture Image
// Bitmap captureImage = (Bitmap) data.getExtras().get("data");
//Set Captue Image to ImageView
imageView.setImageBitmap(mBitmap);
// imageView.setImageBitmap(captureImage);
}
imageView.setImageBitmap(mBitmap); this line is not working so to say.

How can I save and get a image from my database

I take a picture and save the path into my SQLite database but it only saves 0 kb file and when I try to open it with the gallery it is not opening
this is my main activity:
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
Button btnTakePicture;
ImageView imageView;
String pathToFile;
Intent takePictureIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTakePicture = findViewById(R.id.btnTakePicture);
final EditText txtname = (EditText) findViewById(R.id.txtname);
Button mcbutton = (Button) findViewById((R.id.mcbutton));
Button listbutton = (Button) findViewById((R.id.listbutton));
final DataBase db = new DataBase(getApplicationContext());
try {
db.onCreate(db.getWritableDatabase());
} catch (Exception ex) {
}
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
btnTakePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
dispatchTakePictureIntent();
} catch (IOException e) {
e.printStackTrace();
}
}
});
mcbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String fname = txtname.getText().toString();
if (fname == null) {
Toast.makeText(getApplicationContext(), "Please enter something!!", Toast.LENGTH_SHORT).show();
return;
} else if (pathToFile == null) {
Toast.makeText(getApplicationContext(), "Please take a picture!!", Toast.LENGTH_SHORT).show();
return;
} else {
Model model = new Model(fname, pathToFile);
long id = db.ekleModel(model);
if (id > 0) {
Toast.makeText(getApplicationContext(), "Food Registration Perfect! ID = " + id, Toast.LENGTH_LONG).show();
txtname.setText("");
} else {
Toast.makeText(getApplicationContext(), "Please Enter a Food Name", Toast.LENGTH_LONG).show();
}
}
}
});
listbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), Random.class);
startActivity(intent);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
private void dispatchTakePictureIntent() throws IOException {
takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createPhotoFile();
} catch (IOException ex) {
}
}
}
private File createPhotoFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(storageDir, imageFileName + ".jpg");
// Save a file: path for use with ACTION_VIEW intents
pathToFile = image.getAbsolutePath();
return image;
}
and this is my other activity where I get the problem,
everything is supposed to work but I don't know why bitmap decode returns null...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random);
final EditText txtMulti = (EditText)findViewById(R.id.txtMulti);
final ImageView imageView = (ImageView)findViewById(R.id.imageView);
DataBase db = new DataBase(getApplicationContext());
List<Model> modellist = new ArrayList<Model>();
modellist = db.gelModelListesi();
StringBuilder sb = new StringBuilder();
for(Model _model: modellist){
String icerik = "";
icerik = "ID: "+_model.getId()+"Yemek Adı: "+_model.getFoodname()+ "\n\n";
File imgFile = new File(_model.getImagePath());
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getPath());
imageView.setImageBitmap(myBitmap);
}
sb.append(icerik);
}
txtMulti.setText(sb);
}

OnActivityResult: Uri and getData is a null object during capture a photo

I have a problem with Uri object. User should take a photo and next this is sending to Firebase Storage. But sth is wrong with onActivityResult.
I read a lot of topics (https://developer.android.com/training/camera/photobasics.html, StackOverFlow too) but nothing works with this code.
There is an error:
Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
Below is a code:
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
}
As I checked, data (Intent) in onActivityResult is equal to NULL, so uri is null as well.
So, how can I resolve this challenge and make it usable? Should I use a Bitmap to have an access to a photo?
Could someone help me to resolve this situation?
Regards
I figured out with my question.
It works at now.
private ProgressDialog mProgress;
private Button mUploadBtn;
private ImageView mImageView;
Uri picUri;
private StorageReference mStorage;
private static final int CAMERA_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mUploadBtn = (Button) findViewById(R.id.uploadBtn);
mImageView = (ImageView) findViewById(R.id.imageView);
mProgress = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file=getOutputMediaFile(1);
picUri = Uri.fromFile(file); // create
i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file
startActivityForResult(i, CAMERA_REQUEST_CODE);
}
});
}
/** Create a File for saving an image */
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApplication");
/**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;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".png");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK ) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = picUri;
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
Always create your file and store the captured image using the path as follows
File photoFile = null;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
});
}
private File createImageFile() throws IOException {
// Create an image mSelectedFile name
String timeStamp = new SimpleDateFormat(Constants.PHOTO_DATE_FORMAT, Locale.ENGLISH).format(new Date());
String imageFileName = "IMG_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return file;
}
Then use this file "photoFile" and use it as needed in onActivityResult.
I faced the same problem before so i made sure that i check everything i can check when onActivityResult is called below is my code.
First i use this intent to capture image
File photoFile;
URI uri;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null)
{
try
{
photoFile = Create_ImageFile();
}
catch (Exception e)
{
Log.e("file", e.toString());
}
if (photoFile != null)
{
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile.getAbsoluteFile()));
}
}
startActivityForResult(takePhotoIntent, CAMERA_REQUEST_CODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK)
{
try
{
Uri selectedImageURI = null;
ByteArrayOutputStream bos;
Bitmap bitmap = null;
int orientation;
ExifInterface exif = null;
FileOutputStream fos = null;
bos = new ByteArrayOutputStream();
try
{
uri=imageReturnedIntent.getData();
selectedImageURI = imageReturnedIntent.getData();
bitmap= BitmapFactory.decodeFile(GetRealPathFromURI(selectedImageURI));
exif = new ExifInterface(GetRealPathFromURI(selectedImageURI));
fos = new FileOutputStream(GetRealPathFromURI(selectedImageURI));
}
catch (Exception e)
{
e.printStackTrace();
}
if(bitmap==null)
{
uri=Uri.fromFile(photoFile.getAbsoluteFile()));
bitmap=BitmapFactory.decodeFile(photoFile.getAbsolutePath());
exif = new ExifInterface(photoFile.getAbsolutePath());
fos = new FileOutputStream(photoFile.getAbsolutePath());
}
if(bitmap==null)
{
String imagePath = getPathGalleryImage(imageReturnedIntent);
bitmap = BitmapFactory.decodeFile(imagePath);
exif = new ExifInterface(imagePath);
fos = new FileOutputStream(imagePath);
}
Log.e("PhotoFile",photoFile.getAbsolutePath());
// Bitmap bitmap =(Bitmap) imageReturnedIntent.getExtras().get("data");
//bitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(), false);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation ="+orientation);
//exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
//m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
{
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else
{
m.postRotate(0);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
//CropImage.activity(selectedImageURI).setGuidelines(CropImageView.Guidelines.ON).start(this);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
userProfileIMG.setImageBitmap(bitmap);
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
private String getPathGalleryImage(Intent imageURI)
{
Uri selectedImage = imageURI.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 imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
/**
* When image is returned we get its real path
**/
private String GetRealPathFromURI(Uri contentURI)
{
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
// Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private File Create_ImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File mediaStorageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(mediaStorageDir.getAbsolutePath() + File.separator + imageFileName);
return image;
}
after this process i always ended having a bitmap to use it as i want.
For Get Actual Image predefined path of Captured Image using
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
this.startActivityForResult(cameraIntent, 101);
After Captured Image you can get Captured Image on path which is set in cameraIntent. If you don't Want to set predefined path then check Intent data.
if (resultCode == android.app.Activity.RESULT_OK && requestCode == 101) {
try {
path_mm = "Onsuccess_resultcode";
generateNoteOnSD("photo34.txt", path_mm);
Bitmap photo = null;
if (data == null) {
//get Bitmap here.
}
else {
Uri u1 = data.getData();
//get uri and find actual path on that uri.
}
}catch(Exception ex)
{}}

Android Saved images are low quality

I'm taking pictures through the following code and saving to SD card, but the pictures that it produces are such low quality and really bitty even with 100% quality. Maybe bitmap.compress isn't the right way to go (or bitmap at all?!)
Heres my code:
public class TakePhoto extends Activity {
ImageView iv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_photo);
iv = (ImageView) findViewById(R.id.imageView1);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = (Bitmap) data.getExtras().get("data");
Random generator = new Random();
String randFileName = String.valueOf (generator.nextInt(965) + 32);
String both = "/mnt/extSdCard/DirectEnquiries/"+ randFileName + ".jpg";
File imageFile = new File(both);
writeBitmapToMemory(imageFile, bm);
iv.setImageBitmap(bm);
}
public void writeBitmapToMemory(File file, Bitmap bitmap) {
FileOutputStream fos;
try {
Log.e("Tom", "Starting take stream");
fos = new FileOutputStream(file);
Log.e("Tom", "Got stream");
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Log.e("Tom", "Saved Image");
fos.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Please call the below function to capture image from camera.
private final static String FOLDER_NAME = "YourAppName/Image/";
private Uri selectedImageUri = null;
public void startCamera()
{
File photo = null;
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
{
photo = new File(android.os.Environment.getExternalStorageDirectory(), FOLDER_NAME+File.separator+timeStamp+".png");
}
else
{
photo = new File(getCacheDir(), FOLDER_NAME+File.separator+timeStamp+".png");
}
if (photo != null)
{
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
selectedImageUri = Uri.fromFile(photo);
startActivityForResult(intent, CAPTURE_IMAGE_CALLBACK);
}
}
You can get image Uri in selectedImageUri variable . (Image is stored in Sdcard)
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
switch (requestCode)
{
case CAPTURE_IMAGE_CALLBACK:
break;
}
}
Have you tried setting quality in the intent?
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 0);

Categories