How do I save an image after modifying it - java

I can load the picture to the background then I have also been able to "sketchify" it but when I try to save it so that I can email it as an attachment I can only figure out haw to grab the original image and what I have here makes the activity close
public void startCamera(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
seek.setVisibility(View.GONE);
if (takePicture.resolveActivity(getPackageManager()) != null) {
picSpot = new File(Environment.getExternalStorageDirectory(),
"sketch.png");
outputFileUri = Uri.fromFile(picSpot);
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(takePicture, REQUEST_IMAGE_CAPTURE);
}
}
public void sendPic(View v) {
Intent sharePic = new Intent(Intent.ACTION_SEND);
if (didsketch == false) {
sharePic.setType("image/png");
sharePic.putExtra(Intent.EXTRA_STREAM, outputFileUri);
sharePic.putExtra(Intent.EXTRA_SUBJECT, "Check This Out!");
sharePic.putExtra(Intent.EXTRA_TEXT,
"I did this on my Sketchify App!");
startActivity(Intent.createChooser(sharePic, "Send Email"));
} else {
try {
FileOutputStream out = new FileOutputStream(finalSpot);
back.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
outputFileUri = Uri.fromFile(finalSpot);
sharePic.setType("image/png");
sharePic.putExtra(Intent.EXTRA_STREAM, outputFileUri);
sharePic.putExtra(Intent.EXTRA_SUBJECT, "Check This Out!");
sharePic.putExtra(Intent.EXTRA_TEXT,
"I did this on my Sketchify App!");
startActivity(Intent.createChooser(sharePic, "Send Email"));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
sketchit.setEnabled(true);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
screenHeight = metrics.heightPixels;
screenWidth = metrics.widthPixels;
location = Environment.getExternalStorageDirectory()
+ "/sketch.png";
back = Camera_Helpers.processImage(location, screenHeight,
screenWidth);
taken = true;
sketchit.setEnabled(taken);
shareit.setEnabled(taken);
image.setImageBitmap(back);
}
}
back is the modified bitmap i am trying to eventually attach to the email
Thanks!!!

Create Folder Directory and Save image into it: create directory where you want to save your images. Suppose the folder name is ImageFolder.
String location = Environment.getExternalStorageDirectory() + "/ImageFolder/";
//Creating Folder Directory
File imageDir = new File(location);
dir.mkdirs();
//Creating Image file
String imageName = "sketch.png";
File imageFile = new File(imageDir, imageName);
//If image file already exists then delete it.
if (imageFile.exists()) {
imageFile.delete();
}
//Writing the image to SDCard
try {
FileOutputStream out = new FileOutputStream(imageFile);
back.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

Related

Taking Screenshot and Sharing - Android

Trying to Take Screenshot, and Share that image.
Tried bunch of codes, stack, youtube. dont know where is the problem in my code.
Taking screenshot as unknown format. Tried png,jpeg. still remains same.
Screen while share intent
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen);
View rootView = getWindow().getDecorView().getRootView();
Button bat = findViewById(R.id.btsharee);
bat.setOnClickListener(
view ->
shareImage(store(getScreenShot(rootView),"sos.jpeg")));
}
method for screenshot and storing
public static Bitmap getScreenShot(View view) {
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
public static File store(Bitmap bm, String fileName){
final String dirPath = Environment
.getExternalStorageDirectory().getAbsolutePath() +"/Screenshots";
File dir = new File(dirPath);
if(!dir.exists()){
boolean mkdir = dir.mkdir();
}
File file = new File(dirPath, fileName);
try {
FileOutputStream fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG,100, fOut);
fOut.flush();
fOut.close();
return file;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return dir;
}
private void shareImage(File file){
Uri uri;
if (Build.VERSION.SDK_INT < 24) {
uri = Uri.fromFile(file);
uri = Uri.parse(file.getPath());
} else {
uri = Uri.parse(file.getPath());
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/*"); //also tried image/jpeg
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "Msg:" );
try {
startActivity(Intent.createChooser(intent, "Share Screenshot"));
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "No App Available", Toast.LENGTH_SHORT).show();
}
}
I checked storage permission, but storage permission have no problem.
Can anyone help me out..?

Android not capturing camera content view - black screen only - Android 10

So the app I have, takes a photograph (or uses from library) and brings the captured photo into an editing view. The code for the camera capture is;
public void cameraClicked(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 2);
}
The camera view opens, allows me to take a photo, but when it moves to EditorActivity.class the photo is not there, just a black screen. The editor view is fine, but it does not seem to be taking what I capture with the camera. I have set the correct permissions, this works fine in versions prior to Level 23
SDK version.
Edit - updated code methods below;
boolean SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
return false;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 2:
if (resultCode == RESULT_OK) {
Log.e("TAG", "work here");
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
SaveImage(thumbnail);
Intent intent = new Intent(this, EditorActivity.class);
startActivity(intent);
}
break;
}
}

Get image from storage not working in Android

I am capturing an image and store it in storage in mobile but when I get this image it cannot show any thing in Image View. I have tried a lot of code to get images from file but none of them are working in my emulator or real Samsung device.
enter code here
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
// display the image from SD Card to ImageView Control
String storeFilename = "photo_" + partFilename + ".jpg";
Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
imageHolder.setImageBitmap(mBitmap);
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Bitmap getImageFileFromSDCard(String filename){
/* Bitmap bitmap = null;
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
try {
FileInputStream fis = new FileInputStream(imageFile);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap; */
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
// File imgFile = new File(filename);
//("/sdcard/Images/test_image.jpg");
Bitmap myBitmap;
if(imageFile.exists()){
myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
// ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
// myImage.setImageBitmap(myBitmap);
return myBitmap;
}
return null;
}
First of All make sure you have declared the "Access External Storage" and "Access Hardware Camera" permissions in "AndroidManifest" and if you are using Android version 23 or 23+ then you have to take permissions on run-time.
If this is not the problem then use this code given below, it's working fine for me.
For Camera:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, ACTION_REQUEST_CAMERA);
For Gallery:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent chooser = Intent.createChooser(intent, "Choose a Picture");
startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
OnActivityResultMethod:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ACTION_REQUEST_GALLERY:
Uri galleryImageUri = data.getData();
try{
Log.e("Image Path Gallery" , getPath(getActivity() , galleryImageUri));
selectedImagePath = getPath(getActivity() , galleryImageUri);
} catch (Exception ex){
ex.printStackTrace();
Log.e("Image Path Gallery" , galleryImageUri.getPath());
selectedImagePath = galleryImageUri.getPath();
}
break;
case ACTION_REQUEST_CAMERA:
// Uri cameraImageUri = initialURI;
Uri cameraImageUri = data.getData();
Log.e("Image Path Camera" , getPath(cameraImageUri));
selectedImagePath = getPath(cameraImageUri);
break;
}
}
}
Method to get path of Image returned from Camera:
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}

Save a photo selected from gallery to cache directory

I've written a method that creates a directory in my apps cache directory and then prompts the user to take a photo or select a photo from the gallery.
if the user takes a new photo, the photo is saved to the cache as profile.jpg
I'm trying to get the intent that returns a photo from the gallery to save the returned photo in the cache directory of my app as profile.jpg.
I'm having trouble achieving this.
public void selectImage(View v) {
File newDir = new File(getExternalCacheDir(), "RecruitSwift");
if(!newDir.isDirectory())
newDir.mkdirs();
else
Toast.makeText(this, "Dir already exist", Toast.LENGTH_LONG).show();
if(newDir.canWrite())
imageFile = new File(newDir, "profile.jpg");
else
Toast.makeText(this, "Dir not writable", Toast.LENGTH_LONG).show();
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(UserProfileInterviewScreenActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")){
Intent takeProfileImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takeProfileImage.resolveActivity(getPackageManager()) != null) {
Uri imageUri = Uri.fromFile(imageFile);
takeProfileImage.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(takeProfileImage, 1);
}
}
else if (options[item].equals("Choose from Gallery")){
Intent takeProfileImage = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Uri selectedImage = takeProfileImage.getData();
imageFile = selectedImage;
startActivityForResult(takeProfileImage, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
If you want to take a photo or pick a picture, you need to call startActivityForResult and then override onActivityResult. Here are some codes to take a photo, take a look:
startActivityForResult:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra("return-data", false);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(AVATAR_FILE_TMP));
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
startActivityForResult(intent, CODE_TAKE_PHOTO);
then override onActivityResult:
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CODE_TAKE_PHOTO) {
cropImage(Uri.fromFile(AVATAR_FILE_TMP));
}
}
As pointed out by #greenapps the intent it's self doesn't return anything, you have to get the returned content provider path in your onActivityResult method and convert it into a file system path.
This is the code I wrote in the end:
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of profileImage.setImageBitmap(thumbnail);
try{
String file_path = getExternalCacheDir() + "/MyWebsiteDir";
File dir = new File(file_path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "profile.jpg");
FileOutputStream fOut = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (Exception e) {
e.printStackTrace();
}

Getting a crash when taking a picture on Android. Why?

When I take a picture with my device, this code is crashing on the inputStream = line with an error of java.lang.NullPointerException
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uriImage;
InputStream inputStream = null;
ImageView imvCover = (ImageView)this.findViewById(R.id.imvCover);
if ((requestCode == CAPTURE_IMAGE) && resultCode == Activity.RESULT_OK) {
uriImage = data.getData();
try {
inputStream = getContentResolver().openInputStream(uriImage);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, null);
imvCover.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
imvCover.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imvCover.setAdjustViewBounds(true);
}
}
Any ideas why?
This is the code I am using to open the camera to take a picture:
Button btnTakePicture = (Button)this.findViewById(R.id.btnTakePicture);
btnTakePicture.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
try this..
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File out = Environment.getExternalStorageDirectory();
out = new File(out, "newImage.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(out));
startActivityForResult(i, 1);
and this is onActivity result..
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent)
{
super.onActivityResult(requestCode, resultcode, intent);
File out = new File(Environment.getExternalStorageDirectory(), "newImage.jpg");
if(!out.exists())
{
Log.v("log", "file not found");
Toast.makeText(getBaseContext(),
"Error while capturing image", Toast.LENGTH_LONG)
.show();
return;
}
Log.v("log", "file "+out.getAbsolutePath());
File f = new File(out.getAbsolutePath());
try {
ExifInterface exif = new ExifInterface(out.getAbsolutePath());
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
//Toast.makeText(getApplicationContext(), ""+orientation, 1).show();
Log.v("log", "ort is "+orientation);
} catch (IOException e)
{
e.printStackTrace();
}
Bitmap photo =decodeFile(f,400,400);
}
and this is decodeFile Function...
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
This approach may not work for all devices. Instead, you can specify where the new image would be saved, and then you can use that pre-determined file path to work with the new image.
File tempFolder = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/your_folder");
tempFolder.mkdir();
file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/your_folder", String.valueOf(System.currentTimeMillis()) + ".jpg");
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, TAKE_PICTURE);

Categories

Resources