I am working on uploading a photo for user profiles. The goal is to have it both show in the app as a preview, and send it to the database. I am able to do that successfully, however some photos are showing rotated 90 degrees.
I looked up some information on this and it seems that working with ExifInterface is the way to go? (e.g. Image orientation changes while uploading Image to server) but I am not sure how to implement the code I have for firebase with the bitmap to ExifInterface. It's saying its taking media. I've tried casting and putting in a number of different inputs but can't seem to convert what I have. When I looked up converting bitmap there was another article saying it is not possible.
Screenshot of the app(notice photo rotated in bottom left):
The part of my code where this exists is:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if(requestCode == RESULT_OK) {
Log.i("RegisterActivity", "case 0");
}
break;
case 1:
if(resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
Log.i("RegisterActivity", "selected image = " + selectedImage);
//Bitmap imageBitmap = null;
try {
imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage); //The Image/Photo
// https://stackoverflow.com/questions/24629584/image-orientation-changes-while-uploading-image-to-server
//File pictureFile = (File) imageBitmap;
ExifInterface exif= new ExifInterface();
//exif = new ExifInterface();
int angle = 0;
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
}
Matrix matrix1 = new Matrix();
//set image rotation value to 45 degrees in matrix.
matrix1.postRotate(angle);
//Create bitmap with new values.
Bitmap photo = Bitmap.createBitmap(imageBitmap, 0, 0, imageBitmap.getWidth(), imageBitmap.getHeight(), matrix1, true);
profilePhoto.setImageBitmap(imageBitmap); //Placing image in ImageView
The entire code:
public class EditProfileActivity extends Activity {
private EditText firstNameET, lastNameET, passwordET, confirmPasswordET, businessTitleET;
private String firstName, lastName, password, confirmPassword, businessTitle, uid,currentUserString;
private ImageView profilePhoto, xImage, checkmarkImage;
private Button changePhoto;
private DatabaseReference employeesRef;
private FirebaseUser currentUser;
private FirebaseAuth auth;
private AuthCredential credential;
FirebaseStorage storage;
StorageReference storageReference;
private static final int SELECTED_PICTURE = 1;
//Test variable
Uri downloadUrl;
Bitmap imageBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
//INITIALIZE VARIABLES
initVariables();
//UPDATE PHOTO
changePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("photoBTN","InPhotoBTN");
handleChooseImage(view);
}
});
//UPDATE DATA FIELDS
checkmarkImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i("CHECK","INSIDE CHECKMARK");
updateDBFields();
} //END ONCLICK
}); //END ONCLICKLISTENER
}
void initVariables(){
Log.i("initVariables","inside method");
firstNameET = (EditText) findViewById(R.id.firstNameET);
lastNameET = (EditText) findViewById(R.id.lastNameET);
passwordET = (EditText) findViewById(R.id.changePasswordET);
confirmPasswordET = (EditText) findViewById(R.id.passwordConfirmET);
profilePhoto = (ImageView) findViewById(R.id.profilePhoto);
changePhoto = (Button) findViewById(R.id.changePhotoBTN);
xImage = (ImageView) findViewById(R.id.xImage);
checkmarkImage = (ImageView) findViewById(R.id.checkmarkImage);
employeesRef = FirebaseDatabase.getInstance().getReference("Employees");
currentUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserString = currentUser.toString();
Log.i("CurrentUserString", currentUserString);
storage = FirebaseStorage.getInstance();
storageReference = storage.getReferenceFromUrl("gs://timeclock-fc.appspot.com/images").child(currentUserString);
auth = FirebaseAuth.getInstance();
uid = currentUser.getUid();
}
void updateDBFields() {
firstName = firstNameET.getText().toString().trim();
lastName = lastNameET.getText().toString().trim();
password = passwordET.getText().toString().trim();
confirmPassword = confirmPasswordET.getText().toString().trim();
//UPDATE NAME
if(!TextUtils.isEmpty(firstName)) {
Log.i("UID", uid);
employeesRef.child(uid).child("firstName").setValue(firstName);
}
if(!TextUtils.isEmpty(lastName)) {
Log.i("UID", uid);
employeesRef.child(uid).child("lastName").setValue(lastName);
}
//UPDATE PASSWORD
if ( !(TextUtils.isEmpty(password)) && !(TextUtils.isEmpty(confirmPassword)) ) {
if(password.equals(confirmPassword)) {
currentUser.updatePassword(password);
return;
}
}
}
public void encodeBitmapAndSaveToFirebase(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); //was PNG
byte[] data = baos.toByteArray();
UploadTask uploadTask = storageReference.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("OnFailure", exception.toString());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(EditProfileActivity.this, "reached onSuccess:", Toast.LENGTH_SHORT).show();
Log.i("Success", "Reached Success");
//Get the URL of the Image
downloadUrl = taskSnapshot.getDownloadUrl();
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Use a Map for Key/Value pair
Map<String, Object> map = new HashMap<>();
map.put("photoDownloadUrl", downloadUrl.toString());
//Add the URL in the Map to the Firebase DB
employeesRef.child(currentUser.getUid()).updateChildren(map);
}
});
}
//Actually opens the CameraRoll
public void handleChooseImage(View v) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECTED_PICTURE); //then goes to onActivityResult
}
public void handleInsertData(View v) {
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 0:
if(requestCode == RESULT_OK) {
Log.i("RegisterActivity", "case 0");
}
break;
case 1:
if(resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
Log.i("RegisterActivity", "selected image = " + selectedImage);
//Bitmap imageBitmap = null;
try {
imageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage); //The Image/Photo
// https://stackoverflow.com/questions/24629584/image-orientation-changes-while-uploading-image-to-server
//File pictureFile = (File) imageBitmap;
ExifInterface exif= new ExifInterface();
//exif = new ExifInterface();
int angle = 0;
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
}
Matrix matrix1 = new Matrix();
//set image rotation value to 45 degrees in matrix.
matrix1.postRotate(angle);
//Create bitmap with new values.
Bitmap photo = Bitmap.createBitmap(imageBitmap, 0, 0, imageBitmap.getWidth(), imageBitmap.getHeight(), matrix1, true);
profilePhoto.setImageBitmap(imageBitmap); //Placing image in ImageView
}
catch (IOException e) {
e.printStackTrace();
}
encodeBitmapAndSaveToFirebase(imageBitmap);
}
break;
}
}
}
Related
I'm trying to upload an image taken from the camera to the firebase storage, an message dialog appears but it keeps on charging and no images are uploaded to the storage.
Also I'd like to know, how can I get back the image sent from a specific user? should I give the image the user name to the image so I can get it back with his name?
public class ProfileActivity extends AppCompatActivity {
public static final int CAMERA_REQUEST = 10;
private LocationService service;
private Button uploadbtn;
private ImageView imgSpecimentPhoto;
private ImageView imgSpecimentPhoto2;
private ImageView imgSpecimentPhoto3;
private StorageReference storage;
private ProgressDialog mProgress;
Uri photoURI;
String mCurrentPhotoPath;
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 image = File.createTempFile(
imageFileName,
".jpg",
storageDir
);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent(){
Intent takePictureIntent = new Intent (MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity( getPackageManager())!= null){
//Create the file where the photo should go
File photoFile = null;
try{
photoFile = createImageFile();
}catch (IOException ex){
System.out.println("error taking the pic");
}
//Continue only if the file was successfull
if(photoFile != null){
photoURI = FileProvider.getUriForFile( this, "com.example.android.fileprovider",photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult( takePictureIntent, CAMERA_REQUEST );
}
}
}
private View currentView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile );
service = new LocationService(this);
uploadbtn = (Button) findViewById(R.id.upload);
storage = FirebaseStorage.getInstance().getReference();
mProgress = new ProgressDialog( this );
//get access to the image view
imgSpecimentPhoto = findViewById(R.id.camerabtn);
imgSpecimentPhoto2 = findViewById(R.id.camerabtn5 );
imgSpecimentPhoto3 = findViewById(R.id.camerabtn6);
uploadbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProgress.setMessage("Uploading...");
mProgress.show();
dispatchTakePictureIntent();
}
} );
}
public void checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
) {//Can add more as per requirement
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
123);
}
}
public void btnTakePhotoClicked(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
System.out.println("first");
currentView= v;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
photoURI = data.getData();
//did the user chose okay
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
//we are hearing back grom the camera
Bitmap cameraImage = (Bitmap) data.getExtras().get( "data" );
//now we have the image
ImageView cur = (ImageView) currentView;
cur.setImageBitmap( cameraImage );
if (cur.getId() == imgSpecimentPhoto.getId()) {
imgSpecimentPhoto2.setVisibility( View.VISIBLE );
}
if (cur.getId() == imgSpecimentPhoto2.getId()) {
imgSpecimentPhoto3.setVisibility( View.VISIBLE );
StorageReference filepath = storage.child("Photos").child( photoURI.getLastPathSegment());
filepath.putFile( photoURI).addOnSuccessListener( new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(ProfileActivity.this, "Upload Successfull", Toast.LENGTH_SHORT).show();
mProgress.dismiss();
}
} ).addOnFailureListener( new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText( ProfileActivity.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
} );
}
}
}}
when upload image on Firebase used below code ...
bearImage.setDrawingCacheEnabled(true);
bearImage.buildDrawingCache();
Bitmap bitmap = bearImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
// Upload it to our reference
UploadTask uploadTask = bearRef.putBytes(data);
buttonDownload.setEnabled(false);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Log.w(LOG_TAG, "Upload failed: " + exception.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
progressDialog.dismiss();
Log.d(LOG_TAG, "Download Url: " + downloadUrl);
buttonDownload.setEnabled(true);
}
});
remove code for not need in above code..
About getting the image back with the username,
I would upload the photo in the storage with the following path:
// storage/photos/users/userID/photoName
StorageReference storageReference = FirebaseStorage
.getInstanace().getReference
.child("photos/users/" + user_id + "/photoName");
And then I would create a photos node in data base where I would add the userID and then the picture. Something like that:
In this specific case I am storing the user's profile photo into the database. ProfilePhoto model is just the profile image url.
ProfilePhoto profilePhoto = new ProfilePhoto(profile_img_url);
myRef.child("photos").child(user_id).child("photoName").setValue(profile_img_url);
By this way, when I want some user's photo I just get the link from database specifing the userID.
I have an app where user takes a picture and the picture is loaded into the ImageView and then saved in FirebaseStorage. I have problems with fetching images from Firebase (using Picasso) when the internet is slow. How to reduce size of the Bitmap before converting to byte array and saving to Firebase?
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == getActivity().RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageDrawable(makeImageRounded(imageBitmap));
detailViewModel.uploadPhotoToFirebase(imageBitmap);
}
}
Set Permission in the App
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Declare imageView and uri
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;
Firebase storage declare
FirebaseStorage storage;
StorageReference storageReference;
Initilize in onCreate
storage = FirebaseStorage.getInstance(); storageReference =
storage.getReference();
OnClick of button
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
onActivityResult you will get the file path
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
&& data != null && data.getData() != null )
{
filePath = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Upload image to firebase
private void uploadImage() {
if(filePath != null)
{
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
}
});
}
}
Reduce size of specific bitmap to save on firebase
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
call methods - Bitmap converetdImage = getResizedBitmap(bitmap, 500);
I am trying to Compress an Image before Uploading it to Firebase Storage using SiliCompressor library , but it seems not working , the ProgressDialog doesn't stop. What i first did was to pick the Image from the Gallery into an ImageButton by clicking an ImageButton. Below is my code.
imageSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
---------------------------------------------------------------------
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
imageUri = data.getData();
// imageSelect.setImageBitmap(BitmapFactory.decodeFile(imageSelectFile.getAbsolutePath()));
// Compressor com = Compressor.getDefault(this).compressToFile(imageFile);
// imageSelect.setImageURI(imageUri);
Picasso.with(c).load(imageUri).fit().into(imageSelect);
}
}
So now am having a Method startPosting() which Uploads data By a click of Button to Firebase Storage.
Below is my code.
private void startPosting() {
mProgress.setMessage("Uploading Image...");
//Compressing an Image ....
String stringUri= imageUri.toString();
Uri uri_image_final;
//String filePath = SiliCompressor.with(getApplicationContext()).compress(stringUri);
String filePath = SiliCompressor.with(getApplicationContext()).compress(stringUri, true);
uri_image_final = Uri.parse(filePath);
System.out.println("Whats here :" +
""+ uri_image_final);
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mPostDesc.getText().toString().trim();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && filePath != null) {
mProgress.show();
StorageReference filepath = mStorage.child("BlogImages").child(uri_image_final.getLastPathSegment());
filepath.putFile(uri_image_final).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
DatabaseReference c = mDatabase.push();
newPost.child("EventTitle").setValue(title_val);
newPost.child("EventDescription").setValue(desc_val);
newPost.child("EventImage").setValue(downloadUri.toString());
newPost.child("PostId").setValue(c);
mProgress.dismiss();
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
}
);
} else if (TextUtils.isEmpty(title_val) && TextUtils.isEmpty(desc_val) && imageUri != null) {
mProgress.show();
StorageReference filepath = mStorage.child("BlogImages").child(uri_image_final.getLastPathSegment());
filepath.putFile(uri_image_final).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("EventTitle").setValue("");
newPost.child("EventDescription").setValue("");
newPost.child("EventImage").setValue(downloadUri.toString());
mProgress.dismiss();
// startActivity(new Intent(PostActivity.this, MainActivity.class));
Intent load= new Intent(PostActivity.this,MainActivity.class);
load.putExtra(eventname,eventname);
startActivity(load);
}
}
);
}
else if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && imageUri== null){
Toast.makeText(getApplicationContext(),"Please insert an Image and Upload ! ",Toast.LENGTH_LONG).show();
}
}
Now if you see in that Method , my essence was to Compress an Image which is loaded in the ImageButton, then Afterwards it Uploads to firebase.
This is the line of Silicon Compressor which tries to compress an image loaded in the ImageButton.
String filePath = SiliCompressor.with(getApplicationContext()).compress(stringUri, true);
I got this lib from this link of Github.
https://github.com/Tourenathan-G5organisation/SiliCompressor
So where am i wrong please because the Image is not Uploading but i want it to Upload while it's compressed.
Here is what I have written, you can try it.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == Constants.PICK_USER_PROFILE_IMAGE) {
if (resultCode == RESULT_OK) {
Bitmap bmp = ImagePicker.getImageFromResult(this, resultCode, data);//your compressed bitmap here
startPosting(bmp);
}
}
}
}
Your startPosting method should be like this
private void startPosting(Bitmap bmp) {
byte[] data = bmp.toByteArray();
mProgress.setMessage("Uploading Image...");
final String title_val = mPostTitle.getText().toString().trim();
final String desc_val = mPostDesc.getText().toString().trim();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && filePath != null) {
mProgress.show();
StorageReference filepath = mStorage.child("BlogImages").child(uri_image_final.getLastPathSegment());
UploadTask uploadTask = filepath.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
DatabaseReference c = mDatabase.push();
newPost.child("EventTitle").setValue(title_val);
newPost.child("EventDescription").setValue(desc_val);
newPost.child("EventImage").setValue(downloadUri.toString());
newPost.child("PostId").setValue(c);
mProgress.dismiss();
startActivity(new Intent(PostActivity.this, MainActivity.class));
}
});
} else if (TextUtils.isEmpty(title_val) && TextUtils.isEmpty(desc_val) && imageUri != null) {
mProgress.show();
StorageReference filepath = mStorage.child("BlogImages").child(uri_image_final.getLastPathSegment());
UploadTask uploadTask = filepath.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();
newPost.child("EventTitle").setValue("");
newPost.child("EventDescription").setValue("");
newPost.child("EventImage").setValue(downloadUri.toString());
mProgress.dismiss();
// startActivity(new Intent(PostActivity.this, MainActivity.class));
Intent load= new Intent(PostActivity.this,MainActivity.class);
load.putExtra(eventname,eventname);
startActivity(load);
}
});
}
else if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(desc_val) && imageUri== null){
Toast.makeText(getApplicationContext(),"Please insert an Image and Upload ! ",Toast.LENGTH_LONG).show();
}
}
Below is the class ImagePicker that have series of methods to do your work
public class ImagePicker {
private static final int DEFAULT_MIN_WIDTH_QUALITY = 400; // min pixels
private static final String TAG = "ImagePicker";
private static final String TEMP_IMAGE_NAME = "tempImage";
public static int minWidthQuality = DEFAULT_MIN_WIDTH_QUALITY;
public static Bitmap getImageFromResult(Context context, int resultCode,
Intent imageReturnedIntent) {
Log.d(TAG, "getImageFromResult, resultCode: " + resultCode);
Bitmap bm = null;
File imageFile = getTempFile(context);
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage;
boolean isCamera = (imageReturnedIntent == null ||
imageReturnedIntent.getData() == null ||
imageReturnedIntent.getData().equals(Uri.fromFile(imageFile)));
if (isCamera) { /** CAMERA **/
selectedImage = Uri.fromFile(imageFile);
} else { /** ALBUM **/
selectedImage = imageReturnedIntent.getData();
}
Log.d(TAG, "selectedImage: " + selectedImage);
bm = getImageResized(context, selectedImage);
int rotation = getRotation(context, selectedImage, isCamera);
bm = rotate(bm, rotation);
}
return bm;
}
private static Bitmap decodeBitmap(Context context, Uri theUri, int sampleSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(theUri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(
fileDescriptor.getFileDescriptor(), null, options);
Log.d(TAG, options.inSampleSize + " sample method bitmap ... " +
actuallyUsableBitmap.getWidth() + " " + actuallyUsableBitmap.getHeight());
return actuallyUsableBitmap;
}
/**
* Resize to avoid using too much memory loading big images (e.g.: 2560*1920)
**/
private static Bitmap getImageResized(Context context, Uri selectedImage) {
Bitmap bm = null;
int[] sampleSizes = new int[]{5, 3, 2, 1};
int i = 0;
do {
bm = decodeBitmap(context, selectedImage, sampleSizes[i]);
Log.d(TAG, "resizer: new bitmap width = " + bm.getWidth());
i++;
} while (bm.getWidth() < minWidthQuality && i < sampleSizes.length);
return bm;
}
private static int getRotation(Context context, Uri imageUri, boolean isCamera) {
int rotation;
if (isCamera) {
rotation = getRotationFromCamera(context, imageUri);
} else {
rotation = getRotationFromGallery(context, imageUri);
}
Log.d(TAG, "Image rotation: " + rotation);
return rotation;
}
private static int getRotationFromCamera(Context context, Uri imageFile) {
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageFile, null);
ExifInterface exif = new ExifInterface(imageFile.getPath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
public static int getRotationFromGallery(Context context, Uri imageUri) {
String[] columns = {MediaStore.Images.Media.ORIENTATION};
Cursor cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
if (cursor == null) return 0;
cursor.moveToFirst();
int orientationColumnIndex = cursor.getColumnIndex(columns[0]);
return cursor.getInt(orientationColumnIndex);
}
private static Bitmap rotate(Bitmap bm, int rotation) {
if (rotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
Bitmap bmOut = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
return bmOut;
}
return bm;
}
private static File getTempFile(Context context) {
File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
}
The ImagePicker Class have all the methods of handling compression as well as rotation of image.
Hope it will help
Thanks to this link for uploading file ref
Uploading files on firebase
I have done this way:
private void startPosting() {
mProgress.setMessage(getString(R.string.downloading_route));
final String titleVal = mRouteTitle.getText().toString().trim();
final String descVal = mRouteDesc.getText().toString().trim();
if (!TextUtils.isEmpty(titleVal) && !TextUtils.isEmpty(descVal) && mImageUri != null) {
mProgress.show();
StorageReference filepath = mStorage.child("Route images").child(mImageUri.getLastPathSegment());
//compress image
mSelectImage.setDrawingCacheEnabled(true);
mSelectImage.buildDrawingCache();
Bitmap bitmap = mSelectImage.getDrawingCache();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, byteArrayOutputStream);
byte[] data = byteArrayOutputStream.toByteArray();
UploadTask uploadTask = filepath.putBytes(data);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
final Uri downloadUrl = taskSnapshot.getDownloadUrl();
final DatabaseReference newPost = mDatabase.push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
newPost.child("title").setValue(titleVal);
newPost.child("desc").setValue(descVal);
newPost.child("image").setValue(downloadUrl.toString());
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("username").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(AddRouteActivity.this, MainActivity.class));
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
});
}
}
//declear local variable first
Bitmap bitmap;
Uri imageUri;
//button action to call Image picker method
ImageView.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.createChooser(intent,"Pick Image"),GALLERY_REQ_CODE);
}
});
//get bitmap from onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQ_CODE && resultCode == RESULT_OK && data != null) {
imageUri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageURI(imageUri);
}
}
//compress image first then upload to firebase
public void postImage() {
StorageReference storageReference = mStorageRef.child("Images/" + //imageName);
databaseReference = FirebaseDatabase.getInstance().getReference().child("Jobs").child(//imageName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
String path = MediaStore.Images.Media.insertImage(SaveJobActivity.this.getContentResolver(),bitmap,//imageName,null);
Uri uri = Uri.parse(path);
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
final String downloadUrl = task.getResult().toString();
if (task.isSuccessful()){
Map<String, Object> update_hashMap = new HashMap<>();
**//assign download url in hashmap to upadate database reference**
update_hashMap.put("Image",downloadUrl);
**//update database children here**
databaseReference.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
//do what you want
}else {
//show exception
}
}
});
}else{
//show exception
}
}
});
}
});
}
This is my code i capture image and share successfully but can't upload video
public class CaptureActivity extends AppCompatActivity {
ShareButton shareButton;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapture;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri;
private static final String IMAGE_DIRECTORY_NAME = "CityApp";
static File mediaFile;
static File mediaStorageDir;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capture);
imgPreview = (ImageView) findViewById(R.id.imageView);
videoPreview = (VideoView) findViewById(R.id.videoPreview);
btnCapture = (Button) findViewById(R.id.btn_Capture);
shareButton = (ShareButton) findViewById(R.id.fb_share_button);
// shareButton.setFragment(this);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishImage();
// publishVideo();
}
});
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Tack Video", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(CaptureActivity.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 intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
} else if (options[item].equals("Tack Video")) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on scren orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
* Display image from a path to ImageView
*/
private void previewCapturedImage() {
try {
// hide video preview
videoPreview.setVisibility(View.GONE);
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// downsizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
imgPreview.setImageBitmap(bitmap);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Previewing recorded video
*/
private void previewVideo() {
try {
// hide image preview
imgPreview.setVisibility(View.GONE);
videoPreview.setVisibility(View.VISIBLE);
videoPreview.setVideoPath(fileUri.getPath());
// start playing
videoPreview.start();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
public static File getOutputMediaFile(int type) {
// External sdcard location
mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
previewCapturedImage();
} 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();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// preview the recorded video
previewVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void publishImage() {
// statusUpdates= new ContactsContract.StatusUpdates(getActivity().getApplicationContext());
// Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
BitmapFactory.Options options = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("Testing with android")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
shareButton.setShareContent(content);
}
public void publishVideo() {
Uri videoFileUri = fileUri;
ShareVideo shareVideo = new ShareVideo.Builder()
.setLocalUrl(videoFileUri)
.build();
ShareVideoContent content = new ShareVideoContent.Builder()
.setVideo(shareVideo)
.build();
shareButton.setShareContent(content);
}
}
i want use compile 'com.facebook.android:facebook-android-sdk:4.1.0' this library thanks in advance
i want to load image that taken from galllery and camera, when user click on capture button, image will be capture from camera phone device, when user click on add_gallery button, image will be taken from gallery, my problem is when i choose an image from gallery, it is not display on my activity (on My ImageView named by foto_dp).
this is my code :
#Override
public void onClick(View arg0) {
switch (arg0.getId()){
break;
case R.id.capture_dp:
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent, TAKE_PHOTO_CODE);
break;
case R.id.add_galery_dp:
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(i, PICK_FROM_GALLERY);
break;
case R.id.delete_image_dp:
break;
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory() +"/android/data/spaj_foto/spaj_foto("+counter+").png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == TAKE_PHOTO_CODE) {
selectedImagePath = getImagePath();
foto_dp.setImageBitmap(decodeFile(selectedImagePath));
if (requestCode == PICK_FROM_GALLERY) {
selectedImagePath = getImagePath();
foto_dp.setImageBitmap(decodeFile(selectedImagePath));
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
is there anywrong with my code? and how to delete image with a button on my activity? i hope someone can help me to solve my problem, thank you
You do not need to decode file. Try following code
private final int REQUEST_CODE_CAMERA_IMAGE = 1000;
private final int REQUEST_CODE_EXTERNAL_IMAGE = 2000;
//select picture from external storage
btnChoosePicture.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// choose picture from gallery
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,
REQUEST_CODE_EXTERNAL_IMAGE);
}
});
//take picture from camera
btnTakePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// start camera to take picture
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent,
REQUEST_CODE_CAMERA_IMAGE);
}
});
Display image like this
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// get image from camera
case REQUEST_CODE_CAMERA_IMAGE:
if (resultCode == Activity.RESULT_OK) {
imageView.setImageUri(setImageUri());
}
break;
// get image from external storage
case REQUEST_CODE_EXTERNAL_IMAGE:
if (resultCode == Activity.RESULT_OK) {
imageView.setImageUri(data.getData());
}
break;
default:
break;
}
}
To delete image
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(imagePath);
if(file.exist())
file.delete();
}
});
When you get image url from gallery, just delete it like file
button.setOnClickListener(deleteListener);
OnClickListener deleteListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
File file = new File(imagePath);
file.delete();
}
};
Show image use imageview