image upload using parse API - android

I am having trouble trying to upload the image on server using Parse API. I can read from the server and update data on any column except uploading image.
I have picked the image from the device and displayed in imageView..
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
// Set the Image in ImageView after decoding the String
imageView.setImageURI(selectedImage);
Picasso.with(this).load(selectedImage).fit().centerCrop().into(imageView);
//resizing the image part 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//to Compress the image
//Quality Accepts 0 - 100
//0 = MAX Compression (Least Quality which is suitable for Small images)
//100 = Least Compression (MAX Quality which is suitable for Big images)
bitmap.compress(Bitmap.CompressFormat.PNG, 0, baos);
//uploading the image to server
byte[] imageInByte = imgDecodableString.getBytes();
final ParseFile bitmapFile = new ParseFile(imageInByte);
bitmapFile.saveInBackground();
//current user is already logged in.
ParseObject userDisplayImage = new ParseObject("UserDisplayImage");
userDisplayImage.put("photo", bitmapFile);
userDisplayImage.saveInBackground();

In your code :
final ParseFile bitmapFile = new ParseFile(imageInByte);
bitmapFile.saveInBackground();
the bitmapFile is uploaded in a background thread, hence by the time you reach to the next statement :
ParseObject userDisplayImage = new ParseObject("UserDisplayImage");
userDisplayImage.put("photo", bitmapFile);
userDisplayImage.saveInBackground (...);
The bitmapFile is not completely uploaded and hence it userDisaplyImage is not able to make a pointer towards it.
You can try the following to fix it :
final ParseFile bitmapFile = new ParseFile(imageInByte);
bitmapFile.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e==null){
Log.i("hello"," photo saved ");
ParseObject userDisplayImage = new ParseObject("UserDisplayImage");
userDisplayImage.put("photo", bitmapFile);
userDisplayImage.saveInBackground ();
} else {
e.printStackTrace();
Log.i("Error", e + "photo not saved");
}
}
});

Related

Bitmap too large. Tried All

Guys I am facing this issue since 2 days straight. I want to pick an image from gallery and convert it to Base64 method. I have tried Picasso but my imageview is large. Can you please help me. I tried everything but out of memory is too much for me when converting it to bitmap and then to base64.
BitmapDrawable drawable = (BitmapDrawable) ProfilePic.getDrawable();
yourSelectedIBitmapDrawable drawable = (BitmapDrawable) ProfilePic.getDrawable();
yourSelectedImage = drawable.getBitmap();mage = drawable.getBitmap();
Code which is converting this bitmap to Base64. Is there any possibility of skipping the bitmap and directly converting to Base64
private String encodeToBase64(Bitmap image) {
Bitmap immagex = image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
//Log.e("LOOK", imageEncoded);
return imageEncoded;
}
Profile Pic is name of Imageview.
EDIT: So guyz one of the ways is to use the large heap, but Google says you should not use that unless absolutely necessary. The other one that worked for me is the accepted answer. Now I came up with my own solution. In theory, I am using Picasso to load the image into image view. So what if I can extract the image from the ImageView. Not from URI or path, but from Imageview. This way you have an image which is already reduced by Picasso. Picasso provides Callback to for Success or failure. So on Success, you can access the cache memory of ImageView and extract the Bit map out of it.
I will post the code as an answer shortly. I tried it and even an image of 35Mb originally can be converted to bitmap without Out of memory exception.
So here is my ans: https://stackoverflow.com/a/52125006/6022584
You can try to read the bitmap data with a buffer. Something like that :
private String encodeToBase64(Bitmap image) {
// get an InputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(CompressFormat.PNG, 0, baos);
byte[] bitmapdata = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bitmapdata);
// prepare a buffer to read the inputStream
byte[] buffer = new byte[10 * ONE_KIO]; // ONE_KIO = 1024
int bytesRead;
// prepare the stream to encode in Base64
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Base64OutputStream base64OutputStream = new Base64OutputStream(outputStream, Base64.DEFAULT);
// read the inputStream
while ((bytesRead = bais.read(buffer)) != -1) {
base64OutputStream.write(buffer, 0, bytesRead);
}
base64OutputStream.close();
// get the encoded result string
return outputStream.toString();
}
This is my Code that worked. New Issue is the name of Activity for me
if (requestCode == PICK_IMAGE) {
if(resultCode == RESULT_OK){
//isImageFromGallery = true;
//isImageSelected = true;
ImagePath = data.getData();
Picasso.get()
.load(ImagePath)
.resize(1024,1024)
.onlyScaleDown()
.centerCrop()
.into(picture, new Callback(){
#Override
public void onSuccess() {
BitmapDrawable drawable = (BitmapDrawable) picture.getDrawable();
yourSelectedImage = drawable.getBitmap();
//isImageSelected = true;
Log.d("FileSize",Formatter.formatFileSize(NewIssue.this,
yourSelectedImage.getByteCount()));
}
#Override
public void onError(Exception e) {
Toast.makeText(NewIssue.this, "Could Not Load Image", Toast.LENGTH_SHORT).show();
}
});
}
}

upload image to server without compress image

I want to upload image to server without compress it because I am compressing the image in another function and than sending the image to uploadtoserver function.
here is my code to upload the image to server but i dont understand how to upload the image to server without compress it.
public String uploadtoserver(String imgPathm){
//int flag=0;
try{
Bitmap bm = BitmapFactory.decodeFile(imgPathm);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
byte[] ba = bao.toByteArray();
String ba1 = Base64.encodeToString(ba, 0);
//ba1 = Base64.encodeBytes(ba);
return ba1;
}
catch (Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
return null;
}
}
I just want to know will my above code work to upload image to server. thank you

Uploading Image from Android to Node

I am trying to upload multiple images to my node server via Android Studio. However the image file always seems to be corrupt on the server. I am able to take and preview the picture in Android but not able to store it on my server.
Here is my server code
app.post('/upload', function(req, res) {
var base64Data = req.rawBody;
fs.writeFile("test.jpg",base64Data,'base64',function(err,written){
if(err) console.log(err);
else {
console.log("file Succesfully written ");
cloudinary.uploader.upload("test.jpg", function (image) {
if(image !== undefined) {
res.json({link: image.secure_url}).end();
console.log("url = " , image.secure_url);
// fs.unlink(ImageFile);
} else console.log.error("Error uploading to Cloudinary, ", image);
});
}
});
});
Here is my front end code I use to convert my bitmap to an encoded Base64 String.
final String encodedString = ImageBase64.encode(fileArray.get(i));
Here is a log of what encodedString holds after being set. Obviously the full value is not displayed.
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAMgA+gDASIA
AhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA
However on my backend it is displayed as this
2F9j%2F4AAQSkZJRgABAQAAAQABAAD%2F2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2F2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB%0AAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH%2FwAARCAMgA%2BgDASIA%0AAhEBAxEB%2F8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQ
If you get it url encoded then you should url decode it.
InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(uri);//uri is the image URI
Bitmap bm = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] byteArray = baos.toByteArray();
String encodedImage = Base64.encodeToString(byteArray,Base64.NO_WRAP);//encodedImage is your image string
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Unable to locate imageview for uploading to parse

Edit: Solved.
I'm trying to upload an image to parse that has been selected from the phone's gallery. However I cannot seem to locate the imageview as it returns null. I think this page: Saving images to Parse has a similar question to what I'm asking but there is no answer to it.
Fragment class:
public void onClick(View view) {
img = (ImageView) rootView.findViewById(R.id.imageView1);
// Locate the image (error is here)
Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), img);
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
//byte[] image = img.getContext().toString().getBytes();
//Bitmap bitmap = BitmapFactory.decodeFile(img);
ParseFile file = new ParseFile("image.jpg", image);
file.saveInBackground();
ParseObject familyTree = new ParseObject("FamilyTree");
familyTree.put("image", file);
familyTree.put("name", etName.getText().toString());
familyTree.put("relation", etRelation.getText().toString());
familyTree.saveInBackground();
Toast.makeText(FamilyTreeFragment2.this.getActivity(), "Saved.", Toast.LENGTH_SHORT).show();
// getFragmentManager().beginTransaction().replace(R.id.container, new FamilyTreeFragment2()).addToBackStack(null).commit();
}
Any help is appreciated. Thank you.
I've managed to find the solution.
Replaced
Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(), img);
with
Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();

Download and show the Thumbnail

I try to download a picture from URL to SD card/Download.
And I try to show its thumbnail in imageview.
Now I had below code:
try {
Download(URL); //download picture to SD card/Download
File myfile = new File(Environment.getExternalStorageDirectory() + "/Download/", filename);
Drawable photo = null;
photo = Drawable.createFromPath(myfile.getPath());
imageview.setBackgroundDrawable(photo);
}
It show the original picture.
But when the picture is large.
The memory error occurs.
So I want to show the smaller picture.
How should I do to generate the thumbnail and show it?
Or how to use the thumbnail generate by Android system?
Use Bitmap, Something like,
try
{
Download(URL); //download picture to SD card/Download
final int THUMBNAIL_SIZE = 64;
FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + "/Download/", filename);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
imageview.setImageBitmap(imageBitmap);
}
catch(Exception ex) {
}
From the Shown Code
Try this instead your last 2 lines
Bitmap photo = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(myfile.getPath()),60,60,true);
imageview.setImageBitmap(photo);
And if you have made any objects for Bitmap/String/Stream in your Download() function free them calling System.gc();
And I hope this will work.

Categories

Resources