Add multiple pictures into firebase [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I know this question has been asked a lot. But literally non of the answers work for me.
My problem is the images appeared to be saved but on firebase but unfortunately they are the same name so firebase deletes the old one and a inserts a new one. I have done everything i can do to change the name but I can't find a way.
Here is my code for uploading!
private void Fileuploader() throws FileNotFoundException {
String imageid;
imageid = arabic.getText().toString()+"-"+System.currentTimeMillis()+"."+"jpg";
String id = getIntent().getStringExtra("storeid");
member.setImageid(imageid);
reference.child(id).child(arname).setValue(member);
progress.showProgress(profuctadd.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(profuctadd.this);
Cursor getimage = databaseHelper.GetPath();
while (getimage.moveToNext()){
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
byte[] data = out.toByteArray();
System.out.println("IMAGES UPLOADEDDDD: "+ data);
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(profuctadd.this,showProducts.class);
intent.putExtra("spec",getIntent().getStringExtra("spec"));
intent.putExtra("storeid",getIntent().getStringExtra("storeid"));
startActivity(intent);
DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(profuctadd.this,"Failed",Toast.LENGTH_LONG).show();
}
});
}
}
Any ideas?

You're only calculating imageid once across all images, so each image will have the same name. You'll want to calculate a new value for each image, and probably also throw in a counter just to make sure they're all unique:
private void Fileuploader() throws FileNotFoundException {
String id = getIntent().getStringExtra("storeid");
member.setImageid(imageid);
reference.child(id).child(arname).setValue(member);
progress.showProgress(profuctadd.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(profuctadd.this);
Cursor getimage = databaseHelper.GetPath();
int count = 0;
while (getimage.moveToNext()){
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
byte[] data = out.toByteArray();
System.out.println("IMAGES UPLOADEDDDD: "+ data);
StorageReference Ref = mStorageRef.child(imageid);
String imageid = arabic.getText().toString()+"-"+System.currentTimeMillis()+"_"+(count++)+"."+"jpg";
Ref.putBytes(data)
...

Related

How to compress image before upload it to firebase storage?

I want to reduce image file size before I upload it to firebase storage because it take long time to be uploaded.
This is a form which conatins edittext + imageview
I am saving the data(in realtime database) and the image(storage) at the same when clicking on "Save" button.
So how to do to reduce image size or compress it ??
public class PDV_form extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdv_form);
imgproduit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rootNode = FirebaseDatabase.getInstance("https://dtechapp-94795-default-rtdb.europe-west1.firebasedatabase.app");
reference = rootNode.getReference().child("pdv");
String nomcmplt = nomCmplt.getEditText().getText().toString();
String nompdv = nomPdv.getEditText().getText().toString();
String phone = Phone.getEditText().getText().toString();
String adresse = Adresse.getEditText().getText().toString();
String commune = Commune.getEditText().getText().toString();
String wilaya = Wilaya.getEditText().getText().toString();
String codezip = Zip.getEditText().getText().toString();
String email = Email.getEditText().getText().toString();
String imagepdv = placeimgpdv.getDrawable().toString().trim();
UploadDialog = new ProgressDialog(PDV_form.this);
UploadDialog.setTitle("Sauvegarde en cours.... ");
UploadDialog.show();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.FRANCE);
Date now = new Date();
String fileName = formatter.format(now);
storageReference = FirebaseStorage.getInstance().getReference("pdv/" + fileName);
storageReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
placeimgpdv.setImageURI(null);
Toast.makeText(PDV_form.this, "Sauvegarde Terminée", Toast.LENGTH_SHORT).show();
if (UploadDialog.isShowing())
UploadDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (UploadDialog.isShowing())
UploadDialog.dismiss();
Toast.makeText(PDV_form.this, "Sauvegarde Annulée", Toast.LENGTH_SHORT).show();
}
});
StorageReference filpath = storageReference;
filpath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadurl = taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull #NotNull Task<Uri> task) {
String t = task.getResult().toString();
DatabaseReference newPost = reference.child(nomcmplt + "(" + nompdv + ")");
newPost.child("nomcmplt").setValue(nomcmplt);
newPost.child("nompdv").setValue(nompdv);
newPost.child("phone").setValue(phone);
newPost.child("adresse").setValue(adresse);
newPost.child("commune").setValue(commune);
newPost.child("wilaya").setValue(wilaya);
newPost.child("codezip").setValue(codezip);
newPost.child("email").setValue(email);
newPost.child("imagepdv").setValue(task.getResult().toString());
newPost.child("user_id").setValue(uid);
if (task.isSuccessful()) {
startActivity(new Intent(PDV_form.this, Bottom_bar.class));
}
}
});
}
});
}
});
}
private void selectImage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
// intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(intent, Gallery_code);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Gallery_code && resultCode == RESULT_OK) {
imageUri = data.getData();
placeimgpdv.setImageURI(imageUri);
}
}
}
You are asking two questions, one is to reduce the size of the image and the other is to compress it. I am assuming you meant to compress the image in a lossy sort of way by reducing the size and not zip it. Let me know if that is not what you meant in the comments.
One option you have is to build a solution manually. Python has a bunch of good libraries that can help you do this, for java, I did find a few good resources that work along this direction, this SO question seems to be pretty good - How can I compress images using java?
Another option is to use a SaaS tool. This would really simplify the process for you and for something as simple as this, it probably won't even cost anything unless you are compressing a lot of images, or really really large images. As a starting point, you can check out TinyPNG - https://tinypng.com/. They have a developer API - https://tinypng.com/developers.
Edit: Based on new information regarding volume, updating my answer.
Since you are expecting a low amount of images, you can just use TinyPNG. It is pretty simple to get started. You can just sign up, and you get an API key. They have a nice API that you can use in Java - https://tinypng.com/developers/reference/java
I am trying to solve this as well and it appears nothing else is directly helpful to our situation.
The "Possible Duplicate" examples only works if you convert your image to a bitmap. Which almost all examples of what you are trying to achieve do so with bitmaps. Here is some code from that "duplicate" that should help you. Though after I implemented this, I had trouble dealing with rotation.
Uri selectedImageUri = data.getData();
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//here you can choose quality factor in third parameter(ex. i choosen 25)
bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos);
byte[] fileInBytes = baos.toByteArray();
StorageReference photoref = chatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
//here i am uploading
photoref.putBytes(fileInBytes).addOnSuccessListener....etc
Now while this is probably the correct answer. I myself would prefer a cleaner solution that allows me to compress the file via both an InputStream or a Uri, as that is how I upload images to firebase storage as well.
I might be doing the same and dealing with the bitmap directly, but I intend to search for an alternative solution if I can.
To add there is this extension with firebase which will resize after you upload

Get images from firebase storage and realtime database

So, I wanna make the user upload multiple images at the same time to firebase storage. I have done that part successfully but now I want to retrieve the images back. At first, I was uploading one image per user and save the image id to the realtime database so it was very easy to retrieve the image back by the image id. But now how can I save more than one image to the realtime database per user I can't use the same child name because it will be replaced with the old one. Any ideas??
Uploding images and setting the id on realtime database:
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(profuctadd.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(profuctadd.this);
Cursor getimage = databaseHelper.GetPath();
int count = 0;
while (getimage.moveToNext()){
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = arabic.getText().toString()+"-"+System.currentTimeMillis()+"_"+(count++)+"."+getExtension(uri);
System.out.println("IMAGES UPLOADEDDDD: "+ imageid);
String id = getIntent().getStringExtra("storeid");
member.setImageid(imageid);
reference.child(id).child(arname).setValue(member);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(profuctadd.this,showProducts.class);
intent.putExtra("spec",getIntent().getStringExtra("spec"));
intent.putExtra("storeid",getIntent().getStringExtra("storeid"));
startActivity(intent);
DatabaseHelper mDatabaseHelper = new DatabaseHelper(profuctadd.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(profuctadd.this,"Failed",Toast.LENGTH_LONG).show();
}
});
}
}
My firebase db:
you can save more than one image of specific user in images node like that.
DatabaseReference dr = FirebaseDatabase.getInstance().getReference("tL131);
dr.child("images").push().setValue(String.ValueOf(taskSnapshot.getDownloadUrl()));

Can not get download URL for uploaded image to firebase android [duplicate]

This question already has answers here:
How to use getdownloadurl in recent versions?
(5 answers)
How can i upload and retrieve an image to firebase storage in android in 2018 (taskSnapshot/getDownloadUrl deprecated) (Closed)
(3 answers)
Closed 2 years ago.
I have this code which uploads an image from imageview on the click of a button. Even if the image gets uploaded by this code, I'm unable to get the download url for the image which I can use in future reference purposes. Kindly help me in getting the download URL. FYI, the getDownloadURl() function has been deprecated and is not working. Thank you!
Button uploadBtn = findViewById(R.id.upload_btn);
uploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseStorage storage = FirebaseStorage.getInstance();
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl("gs://'''''''.appspot.com/");
// Create a reference to "mountains.jpg"
StorageReference mountainsRef = storageRef.child(System.currentTimeMillis() + ".jpg");
// Create a reference to 'images/mountains.jpg'
StorageReference mountainImagesRef = storageRef.child("images" + System.currentTimeMillis() + ".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
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.
String downloadUrl = taskSnapshot.getMetadata().getReference().getDownloadUrl().toString();
Toast.makeText(ClickImage.this, downloadUrl, Toast.LENGTH_SHORT).show();
}
});
}
});
I got this problem with me before, who gets to download Firebase correctly but not the link in downloadUrl.
After what I searched for the matter, there is a thing called AsyncTask and its method of work works to override the orders that need a greater period of time and executes the orders after it and when it is finished it returns to it
Solve this problem You can use this method to retrieve the value of downloadUrl
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference.getDownloadUrl().addOnCompleteListener(task -> {
String downloadUrl = Objects.requireNonNull(task.getResult()).toString();
});
I hope I simplified things for you and help you .

Data is not inserting to database when image is null

I want to store data into the database and want to upload an image in optional.
It means that if i am inserting the record without adding image then it will store in database without the image name.
right now when i am fill the data and insert an image then it is storing in the database if i don't select any image and i add only data then in database the data is not inserted and showing me blank value in every field
I tried a lot but not getting the required output.
My code main.java
buy_image1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectImage();
edit.putInt("ImageID", 1);
edit.commit();
}
});
public void selectImage()
{
i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
/*i.putExtra("crop", "true");
i.putExtra("outputX", 512);
i.putExtra("outputY", 512);
i.putExtra("aspectX", 1);
i.putExtra("aspectY", 1);
i.putExtra("scale", true);
*/
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
Uri selectedImage = data.getData();
int imgid = 0;
String[] filePathColumn = {MediaStore.MediaColumns.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Log.d("Value", picturePath);
fileName = new File(picturePath).getName();
// imgname.setText(fileName);
String fileNameSegments[] = picturePath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
// MyParams.put("filename", fileName);
Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath);
sp = getActivity().getSharedPreferences("Image ID", Context.MODE_PRIVATE);
imgid = sp.getInt("ImageID", 0);
Log.d("IMGID", Integer.toString(imgid));
BitmapFactory.Options options =null;
options = new BitmapFactory.Options();
options.inSampleSize = 5;
bitmap = BitmapFactory.decodeFile(picturePath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
if(imgid == 1) {
buy_image1.setImageBitmap(yourSelectedImage);
img1 = fileName;
encodedStringIMG1 = encodedString;
}else if(imgid == 2){
buy_image2.setImageBitmap(yourSelectedImage);
img2 = fileName;
encodedStringIMG2 = encodedString;
}
else{
Log.d("IMGID","IMAGE ID IS 0");
}
}
private void InsertWodinformation() {
service(strwodname,strbranch,strcontactperson,strcontact,strwhatsapp,stremail,
strspinnercity,straddress,opendate1,birthdate,ani,strpancard,strtinnumber,strbankname,strbankholdername,strbankac,
strbankcity, strifsccode,strsecuritycheque,strrefrence1,strrefrence2,strremarks,img1,encodedStringIMG1,img2,encodedStringIMG2);
}
private void service(
String strwodname,String strbranch,
String strcontactperson, String strcontact,
String strwhatsapp, String stremail, String strspinnercity,
String straddress, String opendate1, String birthdate, String ani,
String strpancard, String strtinnumber, String strbankname, String strbankholdername
,String strbankac,String strbankcity, String strifsccode,String strsecuritycheque,String strrefrence1,
String strrefrence2,String strremarks,String i1,String encode1,String i2,String encode2
) {
class AddVisitclass extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> param = new HashMap<String, String>();
/*param.put("firm", params[1]);
param.put("oname", params[2]);
param.put("pname1", params[3]);
param.put("pname2", params[4]);
*/
param.put("wname", params[0]);
param.put("branch", params[1]);
param.put("cname", params[2]);
param.put("contact", params[3]);
param.put("whatsapp", params[4]);
param.put("email", params[5]);
param.put("city", params[6]);
param.put("address", params[7]);
param.put("odate", params[8]);
param.put("bdate", params[9]);
param.put("adate", params[10]);
param.put("pancard", params[11]);
param.put("tinno", params[12]);
param.put("bnm", params[13]);
param.put("bank_ac_holder", params[14]);
param.put("bank_ac_no", params[15]);
param.put("bcity", params[16]);
param.put("ifsc_code", params[17]);
param.put("cheque", params[18]);
param.put("ref1", params[19]);
param.put("ref2", params[20]);
param.put("remarks", params[21]);
param.put("pan", params[22]);
param.put("epan", params[23]);
param.put("aadhar", params[24]);
param.put("eaadhar", params[25]);
/*
param.put("light", params[26]);
param.put("elight", params[27]);
param.put("vat", params[28]);
param.put("evat", params[29]);
param.put("vcard", params[30]);
param.put("evcard", params[31]);
param.put("shop", params[32]);
param.put("eshop", params[33]);
*/
param.put("username",uid);
String result = ruc.sendPostRequest(url_addwod, param);
Log.d("Result", result);
Log.d("Data", param.toString());
return result;
}
//#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//loading.dismiss();
Toast.makeText(getActivity(), "W.O.D. added successfully...!!!", Toast.LENGTH_LONG).show();
/* FragmentTransaction t = getActivity().getSupportFragmentManager().beginTransaction();
TabFragment mFrag = new TabFragment();
t.replace(com.Weal.sachin.omcom.R.id.framelayout, mFrag);
t.commit();
*/
}
}
AddVisitclass regi = new AddVisitclass();
regi.execute(strwodname,strbranch,strcontactperson,strcontact,strwhatsapp,stremail,
strspinnercity,straddress,opendate1,birthdate,ani,strpancard,strtinnumber,strbankname,strbankholdername,strbankac,
strbankcity, strifsccode,strsecuritycheque,strrefrence1,strrefrence2,strremarks,i1,encode1,i2,encode2);
}
And one more thing when image is uploading to the server it is generating the lower size but i want it in default size.
The best way to store images/files data is to save the images to the device storage resource (e.g internal memory or external),then you have the image URL/URI saved in your database (instead of having blob field in the database), and to display it all you have to do is to retrieve the file URL and display it on the device.
I hope this gives you a better solution for this issue.
The best way to save images are save them in your computer or device you are using and pass the path (location) of the image through a sql query to the database and when you want to access the image get the location of the image from the database and display.
following link will help you to understand
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
Consider first compressing your images, to reduce the size of the image for storage. You have three options here, first you can get the base64 representation of the image, which is a string then store it , or get the byte array output and still store it. And lastly store the uri reference for the image located on the phone. Though i would not recommend this approach, because it is subjected to path changes and user deletion.
Here is a great library that uses google webp.WebP is a modern image format that provides superior lossless and lossy compression for images.WebP lossless images are 26% smaller in size compared to PNGs. WebP lossy images are 25-34% smaller than comparable JPEG images at equivalent SSIM quality index. Link to library.
Here is a galore of code snippets that can perform your request!
private static String CompressJPEG(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteFormat = stream.toByteArray();
return Base64.encodeToString(byteFormat, Base64.DEFAULT);
}
private static byte[] CompressJPEGByteArray(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
return stream.toByteArray();
}
private static String CompressPNG(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteFormat = stream.toByteArray();
return Base64.encodeToString(byteFormat, Base64.DEFAULT);
}
private static byte[] CompressPNGByteArray(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
private static Bitmap RevertImageBase64(String encodedImage) {
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
}
public static Bitmap RevertFromByteArray(byte[] arr) {
return BitmapFactory.decodeByteArray(arr, 0, arr.length);
}
Here is also code to get the extension from a uri.
public static void GetExtensionFromContentURI(Context context, Uri uri) {
ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = mime.getExtensionFromMimeType(cR.getType(uri));
}
Hope this helps :)
You have to covert bitmap to BLOB format to save it ti db llook below
code :
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encodedData = Base64.encodeToString(byteArray, Base64.DEFAULT);
dba.insertPhoto(byteArray);
Regarding the size issue you mentioned, in onActivityResult(), the statement:
options.inSampleSize = 5;
could be the reason for the file to be smaller than the original image.
This is needed for the ImageView. Before compressing, keep a non compressed coopy for transmission to the server.
To troubbleshoot the insert of the image you need to post:
If the column in the database is defined as "not null"
A Log.d() of the value it is sending to the server when no picture is selected.
The code on the server that receives the data and performs runs the insert.
Refactoring code like below might help you. Don't take method names, variable names and other parts as a real example. I wanted to give you a bird-eye view of sample design.
//controller of user request.
handleRequest(){
String imagePath=null;
if(imageExists){ //if user sent image to server.
imagePath=saveImageAndReturnImagePath(...);
}
saveRecordToDB(request.getText(), imagePath);
}
//save image to disk and return image path.
private String saveImageAndReturnImagePath(...){
//do image manipulation here, save image to disk, return path.
return imagePath;
}
//insert a new record to db.
private void saveRecordToDB(String text, imagePath){
Record a=new Record(text, imagePath);
dao.save(a);
}
The simplest way to cache images . is to use JakeWharton/picasso2-okhttp3-downloader
Here's an example :
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.networkInterceptors().add(new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder().header("Cache-Control", "max-age=" + (60 * 60 * 24 * 365)).build();
}
});
try{
okHttpClient.setCache(new Cache(this.getCacheDir(), Integer.MAX_VALUE));
OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);
Picasso picasso = new Picasso.Builder(this).downloader(okHttpDownloader).build();
picasso.load("pucul").error(R.drawable.teacher).into(imgvw);
}
catch (Exception e){
add this to your gradle file
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
Source :

onActivityResult not called after taking picture

How know that subject is well documented and I have read a lot on that issue, but I still have the following problem: when I take a picture with my app and click on "validate" button, nothing occur. The aime of what I am doing: passing to onActivityReult function not only the thumbnail, but the "whole" picture taken by the camera.
Here is the listener as defined for the "take a picture" button:
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraTest");
mediaStorageDir.mkdir(); // make sure you got this folder
Log.i("Report",mediaStorageDir.toString());
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
try
{
//create directories and the file
mediaFile.getParentFile().mkdirs();
mediaFile.createNewFile();
} catch (IOException e) {
Log.e("Report", "create error for file "+mediaFile);
e.printStackTrace();
}
mFileUri = Uri.fromFile(mediaFile);
Log.i("Report","Uri: "+mFileUri);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);// this line causes issue - onActivityResult not called...
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
and here is the onActivityResult method... that is never called (and that is not declared in the onClickListener method):
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("Report", "1");
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_PIC_REQUEST) {
try {
String[] projection = {
MediaStore.Images.Thumbnails._ID, // The columns we want
MediaStore.Images.Thumbnails.IMAGE_ID,
MediaStore.Images.Thumbnails.KIND,
MediaStore.Images.Thumbnails.DATA };
String selection = MediaStore.Images.Thumbnails.KIND + "=" +
MediaStore.Images.Thumbnails.MINI_KIND;
String sort = MediaStore.Images.Thumbnails._ID + " DESC";
Cursor myCursor = this.managedQuery(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, selection, null, sort);
Log.d("Report", "3");
long imageId = 0l;
long thumbnailImageId = 0l;
String thumbnailPath = "";
try {
myCursor.moveToFirst();
imageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
thumbnailImageId = myCursor
.getLong(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
thumbnailPath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
} finally {
myCursor.close();
}
String[] largeFileProjection = {
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA };
String largeFileSort = MediaStore.Images.ImageColumns._ID
+ " DESC";
myCursor = this.managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection, null, null, largeFileSort);
String largeImagePath = "";
try {
myCursor.moveToFirst();
// This will actually give yo uthe file path location of the
// image.
largeImagePath = myCursor
.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
mImageCaptureUri = Uri.fromFile(new File(
largeImagePath));
} finally {
// myCursor.close();
}
Uri uriLargeImage = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
String.valueOf(imageId));
Uri uriThumbnailImage = Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
String.valueOf(thumbnailImageId));
Bitmap thumbnail = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uriThumbnailImage);
Bitmap image = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uriLargeImage);
But, as said in the title, onActivityResult is not called. Could you please find out why? Because I have tried almost everything I have found on that subject but I should have missed something.
Thanks !
check if you have declared the right permissions in the AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and be sure the file you want to write into exists:
add this below puc_img = new File(photo,"Puc_Img.jpg");
try
{
//create directories and the file
puc_file.getParentFile().mkdirs();
puc_file.createNewFile();
} catch (IOException e) { }
It's not clear from your code but you could be declaring onActivityResult within your onClickListener. If that's true you need to move it.
Take a look at this answer:
OnActivityResult ()
Ok, to solve that issue, I used some "trick" detailed here:
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraTest");
mediaStorageDir.mkdir(); // make sure you got this folder
Log.i("Report",mediaStorageDir.toString());
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
try
{
//create directories and the file
mediaFile.getParentFile().mkdirs();
mediaFile.createNewFile();
} catch (IOException e) {
Log.e("Report", "create error for file "+mediaFile);
e.printStackTrace();
}
tmpFilePath = mediaFile.getPath();
mFileUri = Uri.fromFile(mediaFile);
Log.i("Report","Uri: "+mFileUri);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
So then, I am recovering the file stored in the tmpFilePath, by using that method in the onActivityResult function:
Bitmap image = BitmapFactory.decodeFile(this.tmpFilePath);
And... It's working fine. I still have some issues when sending the file to the WS but that very question have been solved by that piece of code. Thanks for the help, you put me on the track :)

Categories