Cannot resolve symbol - Bitmap image compress and upload to Firebase - android

I'm trying to select an image, compress it and then upload it to the firebase Storage. I'm trying the following code but getting an error that Cannot resolve symbol 'data2'.
This is my activity:
private void openFileChooserOne() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#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) {
mImageUri = data.getData();
Picasso.get().load(mImageUri).into(mImageView);
}
}
private void uploadFile() {
FirebaseUser user = mAuth.getCurrentUser();
String userID = user.getUid();
if (mImageUri != null && mImageMedicalUri != null) {
StorageReference fileReference = mStorageRef.child(userID).child("image.jpg");
try {
Bitmap bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), mImageUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos);
byte[] data2 = baos.toByteArray();
} catch (IOException ioEx) {
ioEx.printStackTrace()
}
mUploadTask = fileReference.putBytes(data2) //Getting error here
.addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//
});
}
})
}
I'm new in Java and trying to understand the problem. Will very much appreciate your help to know what I'm doing wrong here.

When you are using the following line of code:
mUploadTask = fileReference.putBytes(data2)
Your data2 variable is outside the scope where it was declared. To solve this, you should either move this line inside the try-catch block or make the data2 variable as a global variable.

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"

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){
}

Android studio Firebase how to set a picture that a user selected from device storage as a user.PhotoURL

I have no experience in coding and i am just creating a app from tutorials in android studio. I have come a very long way in creating the app. I have implemented the code for selecting a image from the devive gallery and now i wonder how i can set that picture as a Firebase PhotoURL for the current user?
I have implemented that while I was trying firebase. Hope this would do your work.
getImageFromMobile is set to the onClick Method of ImageButton which I am using to set Image to.
public void getImageFromMobile(View view) {
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(intent , galleryRequestCode);
}
private void postDataToFirebase() {
mProgressDialog.setMessage("Posting the Blog to Firebase");
mProgressDialog.setCancelable(false);
final String titleValue = mPostTitle.getText().toString();
final String description = mPostDescription.getText().toString();
if((!TextUtils.isEmpty(titleValue))&& (!TextUtils.isEmpty(description)) && bitmap != null)
{
mProgressDialog.show();
StorageReference filePath = mStorage.child("Blog_Images").child(imagePathName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
String path = MediaStore.Images.Media.insertImage(PostActivity.this.getContentResolver(), bitmap, imagePathName, null);
Uri uri = Uri.parse(path);
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabaseReference.push();
newPost.child("Title").setValue(titleValue);
newPost.child("Desc").setValue(description);
newPost.child("imageUrl").setValue(downloadUrl.toString());
Toast.makeText(PostActivity.this, "Data Posted Successfully to Firebase server", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
Intent intent = new Intent(PostActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == galleryRequestCode && resultCode == RESULT_OK){
Uri imageUri = data.getData();
imagePathName = imageUri.getLastPathSegment();
Log.i("ImagePathName",imagePathName);
Toast.makeText(this, "ImagePathNameto be Checked" + imagePathName, Toast.LENGTH_SHORT).show();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageButton.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}

How to save bitmap to Firebase

I created a simple application which crop the image . Now I want to save this image to the Fire base .
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent imageDownload = new
Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent imageDownload=new Intent();
imageDownload.setAction(Intent.ACTION_GET_CONTENT);
imageDownload.setType("image/*");
imageDownload.putExtra("crop", "true");
imageDownload.putExtra("aspectX", 1);
imageDownload.putExtra("aspectY", 1);
imageDownload.putExtra("outputX", 200);
imageDownload.putExtra("outputY", 200);
imageDownload.putExtra("return-data", true);
startActivityForResult(imageDownload, GALLERY_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK &&
data != null) {
Bundle extras = data.getExtras();
image = extras.getParcelable("data");
photo.setImageBitmap(image);
}
}
How to save this image to the Firebase . I tried many tutorial but could not succeed . Please verify with simple code .
you must first add the dependencies for Firebase Storage to your build.gradle file:
compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
then create an instance of FirebaseStorage:
FirebaseStorage storage = FirebaseStorage.getInstance();
To upload a file to Firebase Storage, you first create a reference to the full path of the file, including the file name.
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://<your-bucket-name>");
// Create a reference to "mountains.jpg"
StorageReference mountainsRef = storageRef.child("mountains.jpg");
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = storageRef.child("images/mountains.jpg");
// While the file names are the same, the references point to different files
mountainsRef.getName().equals(mountainImagesRef.getName()); // true
mountainsRef.getPath().equals(mountainImagesRef.getPath()); // false
Once you've created an appropriate reference, you then call the putBytes(), putFile(), or putStream() method to upload the file to Firebase Storage.
The putBytes() method is the simplest way to upload a file to Firebase Storage. putBytes() takes a byte[] and returns an UploadTask that you can use to manage and monitor the status of the upload.
// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainsRef.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) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
});
Firebase does not support binary data, so you need to convert the image data to base64 or use Firebase Storage
Method 1 ( Recommended )
sref = FirebaseStorage.getInstance().getReference(); // please go to above link and setup firebase storage for android
public void uploadFile(Uri imagUri) {
if (imagUri != null) {
final StorageReference imageRef = sref.child("android/media") // folder path in firebase storage
.child(imagUri.getLastPathSegment());
photoRef.putFile(imagUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot snapshot) {
// Get the download URL
Uri downloadUri = snapshot.getMetadata().getDownloadUrl();
// use this download url with imageview for viewing & store this linke to firebase message data
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// show message on failure may be network/disk ?
}
});
}
}
Method 2
for small images we can still go with this solution, there is firebase field value
limitations(1MB field value)
check official doc for details
public void getImageData(Bitmap bmp) {
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bao); // bmp is bitmap from user image file
bmp.recycle();
byte[] byteArray = bao.toByteArray();
String imageB64 = Base64.encodeToString(byteArray, Base64.URL_SAFE);
// store & retrieve this string which is URL safe(can be used to store in FBDB) to firebase
// Use either Realtime Database or Firestore
}
"firebase-storage 16.0.1"
task.getDowloadUrl() not defined. You can use this i check , working perfectly.
private void firebaseUploadBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();
StorageReference imageStorage = storage.getReference();
StorageReference imageRef = imageStorage.child("images/" + "imageName");
Task<Uri> urlTask = imageRef.putBytes(data).continueWithTask(task -> {
if (!task.isSuccessful()) {
throw task.getException();
}
// Continue with the task to get the download URL
return imageRef.getDownloadUrl();
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String uri = downloadUri.toString();
sendMessageWithFile(uri);
} else {
// Handle failures
// ...
}
progressBar.setVisibility(View.GONE);
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
// Bitmap imageBitmap = data.getData() ;
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (photo != null)
firebaseUploadBitmap(photo);
} else if (requestCode == SELECT_IMAGE && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if (uri != null)
firebaseUploadImage(uri);
}
}

how can I upload a photo from the gallery to parse.com?

I am trying to upload a photo from the gallery into my parse cloud but I can't figure it out here's my code and what I've done so far .
I've looked everywhere still can't find a solution , can't upload the photo :\
help me please.
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
myBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] scaledData = bos.toByteArray();
photoFile = new ParseFile("my_photo.jpg", scaledData);
photoFile.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e != null) {
Toast.makeText(getApplicationContext(),
"Error saving: " + e.getMessage(),
Toast.LENGTH_LONG).show();
} else {
// do something
}
}
});
Save ParseObject in the background
// Create the ParseFile
ParseFile file = new ParseFile("androidbegin.png", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// ParseObject
ParseObject pObject = new ParseObject("ExampleObject");
// Create a column named "ImageName" and set the string
pObject.put("ImageName", "image name here");
// Create a column named "ImageFile" and insert the image
pObject.put("ImageFile", file);
pObject.saveInBackground(); // asynchronous, no callback
Save in the background with callback
pObject.saveInBackground(new SaveCallback () {
#Override
public void done(ParseException ex) {
if (ex == null) {
isSaved = true;
} else {
// Failed
isSaved = false;
}
}
});

Categories

Resources