How to compress image taken by camera before uploading to firebase? - android

I want to pick a picture by camera which is automatically compressed oder converted into a format which is easier to upload.
After that I want to upload the image automatically.
Hope you can help me.
This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mProgressDialog1 = new ProgressDialog(this);
mCamera = (ImageButton) findViewById(R.id.UpCamera);
mImageview = (ImageView) findViewById(R.id.imageView1);
mCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImageview.setImageBitmap(photo);
Toast.makeText(MainActivity.this, "Uploading..", Toast.LENGTH_LONG).show();
mProgressDialog1.setMessage("Crop Image");
mProgressDialog1.show();
Uri uri1 = data.getData();
StorageReference filepath = mStorage.child("Tries").child(uri1.getLastPathSegment());
filepath.putFile(uri1).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgressDialog1.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageview);
Toast.makeText(MainActivity.this, "Upload done!", Toast.LENGTH_LONG).show();
}
});
}
}
}

You need to add this methode then :
Bitmap bmp = BitmapFactory.decodeFile(miFoto)
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", "filename");
like in :Compress camera image before upload

Related

How to upload image on firebase without button android studio

How to upload the image without "upload" button and to use that new image automatically as default user picture? How can I implement this in my code.
mAuth = FirebaseAuth.getInstance();
circlePic = findViewById(R.id.circleImageView);
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
Glide.with(this)
.load(user.getPhotoUrl())
.into(circlePic);
public void Profile(View view) {
Intent cpicview = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(cpicview, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageRIntent) {
super.onActivityResult(requestCode, resultCode, imageRIntent);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK)
mProfileUri = imageRIntent.getData();
Uri selectedImage = imageRIntent.getData();
this.circlePic.setImageURI(selectedImage);
first add click listener to your imageview that will open activity to choose an image
profileImage.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, "Select Profile Image"), REQUEST_CODE);
}
});
then implement onActivityResult that will be executed when image is selected
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE) {
InputStream inputStream = context.getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
uploadImage(bitmap);
}
}
this is the method to upload Bitmap
private void uploadImage(Bitmap bitmap)
{
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("Your url for storage");
StorageReference mountainImagesRef = storageRef.child("images/" + chat_id + Utils.getCurrentTimeStamp() + ".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainImagesRef.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 downloadUrl = taskSnapshot.getDownloadUrl();
Log.d(downloadUrl);
}
});
}
and don't forget to declare REQUEST_CODE in your class
public static final int REQUEST_CODE = 1;
and maybe you will need to add this line in your xml for your profile image view
android:clickable="true"

upload camera image to firebase

I need to store image from camera, and gallery to firebase. In my project upload from gallery working, but when i try to upload from camera nothing happens. When click on button you chose between gallery or camera. When take picture or chose image from gallery, in imageview i get picture. Then i click on save and if picture is from gallery then is saved to storage, and create child in database, but if picture is from camera it won't work. Is there solution for this problem?
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Uri mImageUri = null;
private Button btn,mSubmitBtn;
private ImageView imageview;
private int GALLERY = 1, CAMERA = 2;
private StorageReference mStorage;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
mSubmitBtn = (Button)findViewById(R.id.submit);
imageview = (ImageView) findViewById(R.id.iv);
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Upload");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showPictureDialog();
}
});
mSubmitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
}
});
}
private void showPictureDialog(){
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select photo from gallery",
"Capture photo from camera" };
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
private void takePhotoFromCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA);
}
////////////////////////////
private void startPosting(){
if (mImageUri !=null){
StorageReference filepath = mStorage.child("Images").child(mImageUri.getLastPathSegment());
filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabase.push();//push kreira uniq random id
newPost.child("image").setValue(downloadUrl.toString());
}
});
}
}
////////////////////////
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
mImageUri = data.getData();
imageview.setImageURI(mImageUri);
}
} else if (requestCode == CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageview.setImageBitmap(thumbnail);
imageview.setImageURI(mImageUri);
}
}
}
I faced the same issue and this happens mostly on Kitkat and lower version.When the image is clicked than getting the bitmap file directly try to do following way,
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
e.printStackTrace();
}
imageview.setImageBitmap(thumbnail);
Also in the manifest file make sure you have declared the following permission too along with the READ_EXTERNAL
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Reason for this issue is because Android 4.4 (KitKat) has changed how permissions are handled on the SD card. So its best practice to make your own directory on the SD card to handle all files your app needs to write. This works for all the higher versions too.
Hope this helps.

Firebase Image Upload - Android

I am trying to upload Image to firebase storage but I am neither seeing the progress dialog nor the toast message.
The debug breakpoint is not even stopping at those lines.
Please help.
ib_profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_modifyImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent_modifyImage);
}
});
}
//Image Capture Activity Result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storageReference_image.child("profile_photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UserProfileActivity.this,"Upload Complete",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
try this
public class MainActivity extends AppCompatActivity {
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 111;
Uri filePath;
ProgressDialog pd;
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://fir-example-c4312.appspot.com"); //change the url according to your firebase app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
pd = new ProgressDialog(this);
pd.setMessage("Uploading....");
chooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
uploadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null) {
pd.show();
StorageReference childRef = storageRef.child("image.jpg");
//uploading the image
UploadTask uploadTask = childRef.putFile(filePath);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show();
}
}
});
}
#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 {
//getting image from gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
imgView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
don't forget to Change Rules in firebase console
By default we are not allowed to access firebase storage without authentication. To change it go to firebase console using any web browser. Open the firebase project that you have used in above steps and go to Storage and then Rules tab. Now change read and write rules to true as shown in below image.
try this method,its worked for me
Inside onActivityResult,
StorageReference storageRef = storage.getReferenceFromUrl(---STORAGE_BUCKET---);
StorageReference imagePathReference = storageRef.child("image");
final Uri uri = data.getData();
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
// convert bitmap to byte array to save image in firebase storage
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (bmp != null) {
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bos);
}
byte[] dataNew = bos.toByteArray();
uploadTask = imagePathReference.putBytes(dataNew);
try {
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// success
}
});
}catch (Exception e){
}

Firebase upload photo

I have a code for upload an image to Firebase Storage. The code was running well but when I updated Android Studio there is a problem with code. Can you please suggest how should I change the code?
private StorageReference mStorage;
private static final int GALLERY_INTENT = 2;
private ProgressDialog mProgressDialog;
private ImageView imageViewProfilePicturePreview;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mProgressDialog = new ProgressDialog(this);
mDatabase = FirebaseDatabase.getInstance().getReference();
mStorage = FirebaseStorage.getInstance().getReference();
imageViewProfilePicturePreview = (ImageView) findViewById(R.id.imageViewProfilePicturePreview);
}
...
#Override
public void onClick(View view) {
...
if (view == textViewUploadPhoto) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
}
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
mProgressDialog.setMessage("Uploading...");
mProgressDialog.show();
StorageReference imageRef = mStorage.child(email);
StorageReference imageImagesRef = mStorage.child("photos/" + email);
imageRef.getName().equals(imageImagesRef.getName()); // true
imageRef.getPath().equals(imageImagesRef.getPath()); // false
Uri uri = data.getData();
imageViewProfilePicturePreview.setImageURI(uri);
imageViewProfilePicturePreview.setDrawingCacheEnabled(true);
imageViewProfilePicturePreview.buildDrawingCache();
Bitmap bitmap = imageViewProfilePicturePreview.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data2 = baos.toByteArray();
UploadTask uploadTask = imageImagesRef.putBytes(data2);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getApplicationContext(), "Sorry, your image wasn't set, please try again",
Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent);
Uri downloadUrl = taskSnapshot.getDownloadUrl();
mProgressDialog.dismiss();
Picasso.with(getApplicationContext()).load(downloadUrl).fit().centerCrop().into(imageViewProfilePicturePreview);
Toast.makeText(getApplicationContext(), "Upload done",
Toast.LENGTH_SHORT).show();
}
});
}
}
Thanks for all help.

How to set up an image upload button?

I want to build this app, where you can select one picture from camera or from gallery. This picture is not set as ImageView. Now how can I build an OnClickListener with the uploadbutton, which uploads the image to firebase?
public class MainActivity extends AppCompatActivity {
private StorageReference mStorage;
private static final int GALLERY_INTENT = 2;
private ImageButton mCamera;
private ImageButton mGallery;
private ImageView mImageview;
private static final int CAMERA_REQUEST_CODE = 1;
private ImageButton mUpload;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mGallery = (ImageButton) findViewById(R.id.UpGallery);
mUpload = (ImageButton) findViewById(R.id.UpImage);
mCamera = (ImageButton) findViewById(R.id.UpCamera);
mImageview = (ImageView) findViewById(R.id.imageView1);
mImageview.buildDrawingCache();
mImageview.setDrawingCacheEnabled(true);
mImageview.buildDrawingCache();
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
mGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
mCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent1, CAMERA_REQUEST_CODE);
}
});
mUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
final Uri uri = data.getData();
Picasso.with(MainActivity.this).load(uri).fit().centerCrop().into(mImageview);
}
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImageview.setImageBitmap(photo);
Uri uri1 = data.getData();
Picasso.with(MainActivity.this).load(uri1).fit().centerCrop().into(mImageview);
}
}
}
final StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("gs://{your-storage-name-from-firebase}.appspot.com");
mImageview.setDrawingCacheEnabled(true);
mImageview.buildDrawingCache();
Bitmap bitmap = mImageview .getDrawingCache();
ByteArrayOutputStream baas = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baas);
byte[] data = baas.toByteArray();
UploadTask uploadTask = storageRef.child("{image-folder}").child("unique-id-image").putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this, "Picture upload failed", Toast.LENGTH_LONG).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String downloadUrl = taskSnapshot.getDownloadUrl();
}
});
Hope this helps.

Categories

Resources