Hi Stack Overflow team,
Below is the java code of PhotoEditor Android app for capturing image or choosing the photo from Gallery and then editing and saving the image in the phone.
Following is the MainActivity.java file:
package com.example.photoeditor;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import com.adobe.creativesdk.aviary.AdobeImageIntent;
public class MainActivity extends AppCompatActivity {
public static final String IMAGE_URI = "IMAGE_URI_KEY";
private static final String TAG = "MainActivity";
private static final int IMAGE_EDITOR_RESULT = 1;
private ImageView mEditedImageView;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditedImageView = (ImageView) findViewById(R.id.edited_image_view);
Bundle extras = getIntent().getExtras();
if (extras != null) {
Uri imageUri = Uri.parse(getIntent().getExtras().getString(IMAGE_URI));
Intent imageEditorIntent = new AdobeImageIntent.Builder(this).setData(imageUri).build();
startActivityForResult(imageEditorIntent, IMAGE_EDITOR_RESULT);
finish(); // Comment this out to receive edited image
}
}
// Do something with the edited image
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case IMAGE_EDITOR_RESULT:
Uri editedImageUri = data.getParcelableExtra(AdobeImageIntent.EXTRA_OUTPUT_URI);
Log.d(TAG, "editedImageUri: " + editedImageUri.toString());
Bundle extra = data.getExtras();
if (extra != null) {
boolean changed = extra.getBoolean(AdobeImageIntent.EXTRA_OUT_BITMAP_CHANGED);
Log.d(TAG, "Image edited: " + changed);
if (changed) {
mEditedImageView.setImageURI(editedImageUri);
}
}
break;
default:
throw new IllegalArgumentException("Unexpected request code");
}
}
}
public static Intent getIntent(Context context, Bundle bundle) {
Intent intent = new Intent(context, MainActivity.class);
if (bundle != null) {
intent.putExtras(bundle);
}
return intent;
}
}
Following is the HomeActivity.java file:
package com.example.photoeditor;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.Objects;
import static android.Manifest.permission.CAMERA;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class HomeActivity extends AppCompatActivity {
private static final String TAG = "HomeActivity";
private static final int GALLERY_RESULT = 1;
private static final int CAMERA_RESULT = 2;
private static final String FILE_PROVIDER_AUTHORITY = "com.example.photoeditor";
private static final int CAMERA_PERMISSION_REQ_CODE = 1001;
private static final int STORAGE_PERMISSION_REQ_CODE = 1002;
private String mCapturedImagePath;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
public void openCamera(View view) {
// check for camera permission if not granted before
if (ContextCompat.checkSelfPermission(this, CAMERA) != PERMISSION_GRANTED) {
String[] cameraPermission = { CAMERA };
ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_PERMISSION_REQ_CODE);
} else {
dispatchImageCaptureIntent();
}
}
public void openGallery(View view) {
// check for storage permission if not granted before
if (ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
String[] storagePermissions = { READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE };
ActivityCompat.requestPermissions(this, storagePermissions, STORAGE_PERMISSION_REQ_CODE);
} else {
dispatchGalleryIntent();
}
}
private void dispatchGalleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY_RESULT);
}
private void dispatchImageCaptureIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
if (photoFile != null) {
Uri photoFileUri = FileProvider.getUriForFile(this, FILE_PROVIDER_AUTHORITY, photoFile);
Log.d(TAG, "dispatchImageCaptureIntent:photoFileUri: " + photoFile.toString());
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoFileUri);
startActivityForResult(cameraIntent, CAMERA_RESULT);
}
}
}
#Override public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case CAMERA_PERMISSION_REQ_CODE:
if (grantResults[0] == PERMISSION_GRANTED) {
dispatchImageCaptureIntent();
} else {
Toast.makeText(this, "Required camera permission not granted", Toast.LENGTH_SHORT).show();
}
break;
case STORAGE_PERMISSION_REQ_CODE:
if (grantResults[0] == PERMISSION_GRANTED) {
dispatchGalleryIntent();
} else {
Toast.makeText(this, "Required storage permission not granted", Toast.LENGTH_SHORT)
.show();
}
break;
default:
throw new IllegalArgumentException("Unexpected request code");
}
}
private File createImageFile() throws IOException {
String timeStamp = DateFormat.getDateTimeInstance().format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
mCapturedImagePath = image.getAbsolutePath();
return image;
}
private Bundle uriToBundle(Uri imageUri) {
Bundle bundle = new Bundle();
bundle.putString(MainActivity.IMAGE_URI, imageUri.toString());
return bundle;
}
#Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == GALLERY_RESULT) {
Uri imageUri = data.getData();
startActivity(MainActivity.getIntent(this, uriToBundle(Objects.requireNonNull(imageUri))));
} else if (requestCode == CAMERA_RESULT) {
File imageFile = new File(mCapturedImagePath);
Uri imageUri = Uri.fromFile(imageFile);
startActivity(MainActivity.getIntent(this, uriToBundle(imageUri)));
}
} else {
Toast.makeText(this, "Image not loaded.", Toast.LENGTH_SHORT).show();
}
}
public static Intent getIntent(Context context) {
return new Intent(context, HomeActivity.class);
}
}
Problem what I am facing is, after capturing and editing the photo from the app, when I save the image, the photo does not get saved anywhere in the phone but it says 'Saving...'.
But after saving, app automatically exits
Saving photo is working fine when editing photo from Gallery in the phone. Saving issue is only for camera captured photo through this app.
Can anyone please help with the solution?
Thanks in advance
Try this to save Image
/**
* Save Bitmap file
*
* #param finalBitmap bitmap to store
* #param folderName dst folder
* #param fileName dst filename
* #return Absolute path of file.
*/
public static String saveFileInSDCard(Context context, Bitmap finalBitmap, String folderName, String fileName, Bitmap.CompressFormat compressFormat) {
if (context == null) {
return null;
}
File file = new File(makeDirectory(folderName) + File.separator + fileName + ".png");
if (file.exists()) {
Log.i("fileUtils", "Exists?? " + file.exists()
+ " && " + file.delete());
Log.i("fileUtils", "Exists?? " + file.exists());
}
//to compress bitmap before save
//Bitmap finalBitmap = BitmapUtils.compressSampleBitmap(bitmap,1024);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(compressFormat, 100, out);
out.flush();
out.close();
Log.i(TAG, "Saved: " + file.getAbsolutePath());
/* Update gallery app */
MediaScannerConnection.scanFile(context, new String[]{file.getAbsolutePath()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i(TAG, "Scanned " + path);
}
});
return file.getAbsolutePath();
} catch (Throwable e) {
e.printStackTrace();
Log.e(TAG, "Error: " + e.getMessage());
return null;
}
}
public static String makeDirectory(String folderName) {
File myDir = new File(root + "/" + folderName);
if (!myDir.exists()) {
Log.i(TAG, "Making Folder ->" + myDir.getName());
//will create only single dir
//myDir.mkdir();
//will create all required directory specified in the path
myDir.mkdirs();
}
return myDir.getAbsolutePath();
}
Related
i'm having issue doing image center crop to a specific size after taking a still photo by calling MediaStore.ACTION_IMAGE_CAPTURE.
Action Image Capture currently stores the image to image directory, how do i crop image automatically according to my pre-set size and save it to the same path and filename?
appreciate if can give some guidance. im new to android
i do have the URI of the image, just wondering if there's any way to center crop, resize to a specific size eg: 456x456 and save the image to the same URI by overwriting.
below is my code under MainActivity:
package com.example.android_take_photos_and_save_gallery;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
public static final int CAMERA_PERM_CODE = 101;
public static final int CAMERA_REQUEST_CODE = 102;
ImageView selectedImage;
Button cameraBtn;
String currentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedImage = findViewById(R.id.displayImageView);
cameraBtn = findViewById(R.id.cameraBtn);
// Open Camera
cameraBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifyPermissions();
}
});
}
private void verifyPermissions(){
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
permissions[0]) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this.getApplicationContext(),
permissions[1]) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this.getApplicationContext(),
permissions[2]) == PackageManager.PERMISSION_GRANTED){
dispatchTakePictureIntent();
}else{
ActivityCompat.requestPermissions(this,
permissions,
CAMERA_PERM_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == CAMERA_PERM_CODE){
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
dispatchTakePictureIntent();
}else {
Toast.makeText(this, "Camera Permission is Required to Use camera.", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE){
if(resultCode == Activity.RESULT_OK){
File f = new File(currentPhotoPath);
selectedImage.setImageURI(Uri.fromFile(f));
Log.d("tag", "ABsolute Url of Image is " + Uri.fromFile(f));
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
// File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
}
I am facing an issue which I do not understand. I am taking a picture then creating a PNG image file as per code that follows but somewhere down the line a random string is being added to the filename which causes me all sorts of issues. For example (as per tutorials I have found): I create an image called dimage_(generated timestamp) and save the string to shared preferences and the image in getExternalFilesDir(Environment.DIRECTORY_PICTURES). In shared preferences the string is correct but the file has the above mentioned string appended.
Eg:
The generated filename string saved in shared prefs:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="driver_picture">dimage_20190610_065509</string>
</map>
Whereas the file checked with adb results as:
127|generic_x86:/storage/emulated/0/Android/data/africa.mykagovehicledrivers/files/Pictures $ ls
dimage_20190610_0655091215099619.png
generic_x86:/storage/emulated/0/Android/data/africa.mykagovehicledrivers/files /Pictures $
I have no clue where the 1215099619 extra part comes from!
This is the code of the activity:
package africa.mykagovehicledrivers;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.yalantis.ucrop.UCrop;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class RegisterDriverImage extends AppCompatActivity {
String currentPhotoPath;
final int REQUEST_TAKE_PHOTO = 1;
final int CAMERA_PERMISSIONS = 3;
Activity activity = this;
ImageView imgTakePicture, imgDriver;
Button btnContinueDriver;
ProgressBar prgImage;
SharedPreferences prefs;
SharedPreferences.Editor edit;
String imageFileName;
Tools t;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good so launch take picture from here
dispatchTakePictureIntent();
} else {
// Permission denied. Warn the user and kick out of app
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.permsDeniedCameraTitle);
builder.setMessage(R.string.permsDeniedCameraMessage);
builder.setCancelable(false);
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
});
builder.create().show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Uri starturi = Uri.fromFile(new File(currentPhotoPath));
Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
UCrop.Options options = AppConstants.setUcropOptions(activity);
UCrop.of(starturi, destinationuri).withOptions(options).start(activity);
}
// On result from cropper add to image view
if (resultCode == RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
prgImage.setVisibility(View.VISIBLE);
final Uri resultUri = UCrop.getOutput(data);
assert resultUri != null;
File imgFile = new File(resultUri.getPath());
Picasso.Builder builder = new Picasso.Builder(getApplicationContext());
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
builder.build().load(imgFile).into(imgDriver, new Callback() {
#Override
public void onSuccess() {
Log.d("-------->", "onSuccess: CROPPED!");
prgImage.setVisibility(View.INVISIBLE);
btnContinueDriver.setEnabled(true);
}
#Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_driver_image);
prefs = getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
edit = prefs.edit();
imgTakePicture = findViewById(R.id.imgTakePicture);
imgDriver = findViewById(R.id.imgDriver);
btnContinueDriver = findViewById(R.id.btnContinueDriver);
prgImage = findViewById(R.id.prgImage);
t = new Tools(getApplication(), getApplicationContext(), this);
imgTakePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
imgDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btnContinueDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putString("driver_picture", imageFileName);
edit.putString("nextstep", "drivinglicense");
edit.apply();
Intent drivinglicense = new Intent(getApplicationContext(), RegisterDrivingLicense.class);
startActivity(drivinglicense);
finish();
}
});
// Always ask for camera permissions
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CAMERA }, CAMERA_PERMISSIONS);
}
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("IMAGE CREATION FAILED", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"africa.mykagovehicledrivers.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
imageFileName = "dimage_" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".png",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
As per code I am using String imageFileName; to save the path and then use it in the button click action to save it into shared preferences.
Thanks!
Found out the reasin. createTempFile does this. Switched to new File() and this solved the issue.
I am writing a scavenger hunt type app that allows for the user to take one or two photos of a bonus location and then submit those images via email. However, I can't seem to get it to put both images in the email, it only gets the most recent one.
I found this answer: Cant send email with multiple attachment in android programmatically, which seems to say that I must do this using an array, but the example there doesn't seem to match at all what I'm doing so I'm not certain how to make the array.
Below is my current code. Could someone tell me how to make my two EXTRA_STREAMS into the requisite array (or point me in the correct direction if that is not the proper fix)?
package net.tommyc.android.tourofhonor;
import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
public class captureBonus extends AppCompatActivity {
/**
* Opens an already installed Camera application
*/
static final int REQUEST_TAKE_PHOTO = 1;
int riderNumToH = 479;
int pillionNumToH = 000;
String submissionEmailAddress = "me#tommyc.net";
Button btnTakeMainPic;
Button btnSubmitBonus;
ImageView imageViewMain;
ImageView imageViewSecondary;
int tappedImageView = 3;
File mainPhotoUri = null;
File secondaryPhotoUri = null;
/**
* Saves the full size image to the public photo directory (similar to the Camera Roll on iOS)
* * saveImage(imageName: "2018_\(riderNumToH)_\(bonusCodeLabel.text!)_1.jpg")
*/
String mainPhotoPath;
String secondaryPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture_bonus);
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
btnSubmitBonus = findViewById(R.id.btnSubmitBonus);
btnSubmitBonus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchSubmitBonusIntent();
}
});
imageViewMain = findViewById(R.id.bonusMainImage);
imageViewMain.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tappedImageView = 0;
dispatchTakeMainPictureIntent();
Log.v("User Action", "Main Image Tapped");
}
});
imageViewSecondary = findViewById(R.id.bonusSecondaryImage);
imageViewSecondary.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
tappedImageView = 1;
dispatchTakeMainPictureIntent();
Log.v("User Action", "Main Image Tapped");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
if (tappedImageView == 0) {
Bitmap bitmap = BitmapFactory.decodeFile(mainPhotoPath);
imageViewMain.setImageBitmap(bitmap);
} else if (tappedImageView == 1) {
Bitmap bitmap = BitmapFactory.decodeFile(secondaryPhotoPath);
imageViewSecondary.setImageBitmap(bitmap);
} else {
Log.w("ERROR", "onActivityResult: valid view ID not found (" + tappedImageView + ")");
}
}
}
}
private void dispatchTakeMainPictureIntent() {
Intent takeMainPictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takeMainPictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
if (tappedImageView == 0) {
mainPhotoUri = createImageFile();
} else if (tappedImageView == 1) {
secondaryPhotoUri = createImageFile();
}
} catch (IOException ex) {
// Error occurred while creating the File
Log.e("fileCreationError", "An error occurred while creating the image file.");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(captureBonus.this, "net.tommyc.android.tourofhonor", photoFile);
takeMainPictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takeMainPictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String imagePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString();
String mainImageFileName = "2019_" + riderNumToH + "_BonusCode_1.jpg";
String secondaryImageFileName = "2019_" + riderNumToH + "_BonusCode_2.jpg";
if (tappedImageView == 0) {
File capturedImage = new File(imagePath, mainImageFileName);
mainPhotoPath = capturedImage.getAbsolutePath();
return capturedImage;
} else if (tappedImageView == 1) {
File capturedImage = new File(imagePath, secondaryImageFileName);
secondaryPhotoPath = capturedImage.getAbsolutePath();
return capturedImage;
} else {
Log.w("ERROR", "createImageFile: valid view ID not found (" + tappedImageView + ")");
}
return null;
}
/**
* Submits the bonus images via email.
*/
private void dispatchSubmitBonusIntent() {
Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
sendEmailIntent.setType("plain/text");
sendEmailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{submissionEmailAddress});
sendEmailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "2019_" + riderNumToH + "_BonusCode");
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, "Sent from TOH App\nAndroid Version 0.3.076");
if (mainPhotoPath != null) {
sendEmailIntent.putExtra(android.content.Intent.EXTRA_STREAM, FileProvider.getUriForFile(captureBonus.this, "net.tommyc.android.tourofhonor", mainPhotoUri));
Log.v("MainImageFound", mainPhotoPath + "|" + mainPhotoUri);
if (secondaryPhotoPath != null) {
sendEmailIntent.putExtra(android.content.Intent.EXTRA_STREAM, FileProvider.getUriForFile(captureBonus.this, "net.tommyc.android.tourofhonor", secondaryPhotoUri));
Log.v("SecondaryImageFound", secondaryPhotoPath + "|" + secondaryPhotoUri);
} else {
Log.e("NoImageFound", "Image Not Found");
}
}
this.startActivity(Intent.createChooser(sendEmailIntent, "Sending email..."));
}
}
You should put all your files Uri's to Arraylist<Parcelable> then put it to intent by intent.putParcelableArrayListExtra
In my project, I am capturing image from the camera. I am taking the full-size image from the app (instead of taking thumbnail). Captured image is of very big size which is 7 to 18 mb. When I have taken image from my default camera app, the size was roughly 2.5 mb only. As well as it's taking lot of time(6-10 seconds) to load and save to the folder. This happening only when I am using the android device, on emulator it's working good. This is my code:
package com.stegano.strenggeheim.fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.stegano.strenggeheim.BuildConfig;
import com.stegano.strenggeheim.R;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
public class FragmentEncode extends Fragment {
private static final String MESSAGE_IMAGE_SAVED = "Image Saved!";;
private static final String MESSAGE_FAILED = "Failed!";
private static final String IMAGE_DIRECTORY = "/StrengGeheim";
private static final int GALLERY = 0, CAMERA = 1;
private File capturedImage;
TextView imageTextMessage;
ImageView loadImage;
public FragmentEncode() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
private void galleryIntent() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri fileUri = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA);
}
private Uri getOutputMediaFileUri() {
try {
capturedImage = getOutputMediaFile();
return FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".provider", capturedImage);
}
catch (IOException ex){
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_encode, container, false);
imageTextMessage = view.findViewById(R.id.imageTextMessage);
loadImage = view.findViewById(R.id.loadImage);
loadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
return view;
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(getContext());
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera",
"Cancel"
};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
galleryIntent();
break;
case 1:
cameraIntent();
break;
case 2:
dialog.dismiss();
break;
}
}
});
pictureDialog.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_CANCELED) {
return;
}
try {
if (requestCode == GALLERY && data != null) {
Bitmap bitmap = getBitmapFromData(data, getContext());
File mediaFile = getOutputMediaFile();
String path = saveImage(bitmap, mediaFile);
Log.println(Log.INFO, "Message", path);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
loadImage.setImageBitmap(bitmap);
imageTextMessage.setVisibility(View.INVISIBLE);
} else if (requestCode == CAMERA) {
final Bitmap bitmap = BitmapFactory.decodeFile(capturedImage.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
saveImage(bitmap, capturedImage);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(getContext(), MESSAGE_FAILED, Toast.LENGTH_SHORT).show();
}
}
private Bitmap getBitmapFromData(Intent intent, Context context){
Uri selectedImage = intent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver()
.query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return BitmapFactory.decodeFile(picturePath);
}
private String saveImage(Bitmap bmpImage, File mediaFile) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmpImage.compress(Bitmap.CompressFormat.PNG, 50, bytes);
try {
FileOutputStream fo = new FileOutputStream(mediaFile);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(getContext(),
new String[]{mediaFile.getPath()},
new String[]{"image/png"}, null);
fo.close();
return mediaFile.getAbsolutePath();
} catch (IOException ex) {
ex.printStackTrace();
}
return "";
}
private File getOutputMediaFile() throws IOException {
File encodeImageDirectory =
new File(Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
if (!encodeImageDirectory.exists()) {
encodeImageDirectory.mkdirs();
}
String uniqueId = UUID.randomUUID().toString();
File mediaFile = new File(encodeImageDirectory, uniqueId + ".png");
mediaFile.createNewFile();
return mediaFile;
}
}
Something you could do is download an available API online, or, if need be, dowload the source code of some online compressor. Then you could use it as a model. Never directly use the source code. One that is widely supported across languages is: https://optimus.keycdn.com/support/image-compression-api/
I am taking the image from the camera and getting the File. So, I am saving the image directly in file location which I generated using getOutputMediaFile() method. For that I am overloading saveImage() method like this:
private void saveImage(File mediaImage) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(mediaImage);
mediaScanIntent.setData(contentUri);
getContext().sendBroadcast(mediaScanIntent);
}
This method will put the image in the desired file location and also accessible to the Gallery for other apps. This method is same as galleryAddPic() method on this link Taking Photos Simply
But In the case of picking a photo from the Gallery, I will have to create the File in the desired location and write the bytes of the picked image into that file, so the old saveImage() method will not change.
In onActivityResult method, this is how I used overloaded saveImage() method:
else if (requestCode == CAMERA) {
saveImage(imageFile);
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
loadImage.setImageBitmap(bitmap);
Toast.makeText(getContext(), MESSAGE_IMAGE_SAVED, Toast.LENGTH_SHORT).show();
imageTextMessage.setVisibility(View.INVISIBLE);
}
i am working on google drive and try to intrgate in my app.lots of thing i have done.
first i craete SH1 key and then enable the drive api and then genrate the APP key.now i
have implement this link but when i pick the image from gallery it redirect back on this activity and i print the path of image it gives correct path and doesn't uploading.
what i do now??please anybody help me i m struck here what i do now cannot understand.
https://developers.google.com/drive/quickstart-android#step_4_set_up_the_sample
import java.io.IOException;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
public class MainActivity extends Activity{
private static final int REQUEST_ACCOUNT_PICKER = 1;
private static final int SELECT_PICTURE = 3;
private static final int REQUEST_AUTHORIZATION = 2;
private static Drive service;
private GoogleAccountCredential credential;
private static Uri selectedImageUri;
private String selectedImagePath;
private ImageView img;
private TextView tv;
Intent pictureintent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// img = (ImageView)findViewById(R.id.ImageView01);
((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
pictureintent = new Intent();
pictureintent.setType("image/jpeg");
pictureintent.setAction(Intent.ACTION_GET_CONTENT);
pictureintent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
startActivityForResult(pictureintent, SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode){
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
service = getDriveService(credential);
saveFileToDrive();
}
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == Activity.RESULT_OK) {
saveFileToDrive();
} else {
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
case SELECT_PICTURE:
if (resultCode == Activity.RESULT_OK) {
selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
// tv = (TextView) findViewById(R.id.text1);
//tv.setText("File Path: " + selectedImagePath);
showToast("File Path: " + selectedImagePath);
System.out.println("Image Path : " + selectedImagePath);
//img.setImageURI(selectedImageUri);
startpictureIntent();
}
}
}
private Drive getDriveService(GoogleAccountCredential credential) {
return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential)
.build();
}
public void startpictureIntent(){
credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
private void saveFileToDrive() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
// File's binary content
java.io.File fileContent = new java.io.File(selectedImageUri.getPath());
FileContent mediaContent = new FileContent("image/jpeg", fileContent);
// File's metadata.
File body = new File();
body.setTitle(fileContent.getName());
body.setMimeType("image/jpeg");
File file = service.files().insert(body, mediaContent).execute();
if(file != null) {
showToast("Photo uploaded: " + file.getTitle());
}
}catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void showToast(final String toast) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), toast, Toast.LENGTH_LONG).show();
}
});
}
}
I too use almost the same code for uploading a pdf file, but it is working for me,
try
{
FileContent mediaContent = new FileContent("application/pdf",pdfFile);
com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle(filename);
body.setMimeType("application/pdf");
com.google.api.services.drive.model.File file = servicer.files().insert(body,mediaContent).execute();
if (file != null)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(getApplicationContext(), "File exported successfully", 2000);
toast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 30);
toast.show();
}
}
);
}
}
catch (UserRecoverableAuthIOException e)
{
startActivityForResult(e.getIntent(),REQUEST_AUTHORIZATION);
}
catch (IOException e)
{
e.printStackTrace();
}