How to Upload an Image in Parse Server Using Parse API in Android

How to upload an image in parse server using parse api in android

Save ParseObject in the background

// ParseObject
ParseObject pObject = new ParseObject("ExampleObject");
pObject.put("myNumber", number);
pObject.put("myString", name);
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;
}
}
});

Variations of the save...() method include the following:

    saveAllinBackground() saves a ParseObject with or without a callback.
saveAll(List<ParseObject> objects) saves a list of ParseObjects.
saveAllinBackground(List<ParseObject> objects) saves a list of ParseObjects in the
background.
saveEventually() lets you save a data object to the server at some point in the future; use
this method if the Parse cloud is not currently accessible.

Once a ParseObject has been successfully saved on the Cloud, it is assigned a unique Object-ID. This Object-ID is very important as it uniquely identifies that ParseObject instance. You would use the Object-ID, for example, to determine if the object was successfully saved on the cloud, for retrieving and refreshing a given Parse object instance, and for deleting a particular ParseObject.

I hope you will solve your problem..

How to upload image to Parse in android?

reading your answer :

I already followed the code that you have before. I was able to upload the image to parse. but I dont know how to switch the drawable source to be my image from camera/gallery or imageview. – stanley santoso

to :

Abhishek Bansal

I understand that your problem is not parsing your image ?

To try to answer your question :

I dont know how to switch the drawable source to be my image from camera/gallery or imageview.

1 - R.drawable.androidbegin seems to be your problem BUT the fact is that you already have your bitmap to parse in your code :

from gallery ->

mImageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

from camera ->

Bitmap photo = (Bitmap) data.getExtras().get("data");

2 - So I would suggest to declare a variable of type Bitmap at the beginning of your code

private Bitmap yourbitmap;

3 - then assign the bitmap for the gallery and the camera in your code and use it to parse it.

...
yourbitmap = BitmapFactory.decodeFile(picturePath);
...
yourbitmap = (Bitmap) data.getExtras().get("data");
...

4 - finally you can use your bitmap like so :

//    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
// R.drawable.androidbegin);
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
yourbitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] image = stream.toByteArray();
...

How to Upload the image from gallery to Parse Server in android..?

Change this line from

ParseFile file = new ParseFile("androidbegin.png", image,"image/png");

to

ParseFile file = new ParseFile("androidbegin.png", image);

And have you added these lines,

            ParseObject photo = new ParseObject("Photo");
photo.put("fileFull", imgfile);
photo.put("User", ParseUser.getCurrentUser());
photo.saveInBackground();

How do I upload an image to Parse Server using Kotlin/Jvm via Rest Service?

If you're using Back4App, the correct Server URL is:

https://parseapi.back4app.com/files/pic.jpg

Parse.com & Android: How do I save Images to my parse database so that i can use them as a profile picture

I have no experience with parse.com but If you are able to put images(bit map) into ParseObject, you just need to call take photo or pick photo action using intent and startActivityForResult. Example:

public void onClickTakePhoto(View view) {
dispatchTakePictureIntent();
}
public void onClickPickPhoto(View view) {
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, REQUEST_SELECT_IMAGE);
}
//Code from Android documentation
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == REQUEST_IMAGE_CAPTURE || requestCode == REQUEST_SELECT_IMAGE) && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ParseObject statusObject = new ParseObject("Status");
//I think parse has similar support If not this
statusObject.put("profile_photo",imageBitmap);
statusObject.saveInBackground( new Callback(){...});

}
}

How to pick image from gallery and upload to server (parse.com) ?

try to this way for pickup image from camera & gallery.

// this is local variable.
String selectedImagePath, ServerUploadPath = "" + "", str_response;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int SELECT_PICTURE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Hello Camera";
static File mediaFile;
private Uri fileUri; // file url to store image/video

this method for camera & Gallery image pick up.

public void cameraAndGalaryPicture() {
final String[] opString = { "Take Photo", "Choose From Gallery",
"Cancel" };

AlertDialog.Builder dbuilder = new AlertDialog.Builder(this);
dbuilder.setTitle("Add Photo!");

dbuilder.setItems(opString, new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
if (opString[which].equals("Take Photo")) {
fromCamera();
} else if (opString[which].equals("Choose From Gallery")) {
fromFile();
} else {
// Picasso.with(getApplicationContext())
// .load(R.drawable.default_image).resize(360, 200)
// .into(iv_Profile_pic);
rotatedBMP = BitmapFactory.decodeResource(getResources(),
R.drawable.default_image);
Global.mImage = rotatedBMP;
Log.e("Else if", "msg::19th Feb- " + rotatedBMP);
Log.e("Else if", "msg::19th Feb- " + Global.mImage);
// dialog.dismiss();
}

}
});

dbuilder.show();
}

public void fromCamera() {

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

}

public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}

private static File getOutputMediaFile(int type) {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);

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 {
return null;
}
Log.e("path", "media file:-" + mediaFile);
return mediaFile;
}

public void fromFile() {

Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select File"),
SELECT_PICTURE);
}

public String getPath(Uri uri, Activity activity) {
String[] projection = { MediaColumns.DATA };
Cursor cursor = activity
.managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

this method for compress image

private void previewCapturedImage() {
try {

int targetW = 380;
int targetH = 800;
Log.d("Get w", "width" + targetW);
Log.d("Get H", "height" + targetH);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;

// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);

// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor << 1;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath,
bmOptions);

Matrix mtx = new Matrix();

try {

File imageFile = new File(selectedImagePath);

ExifInterface exif = new ExifInterface(
imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.e("Orintation", " :-" + orientation);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:

mtx.postRotate(270);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_Profile_pic.setImageBitmap(rotatedBMP);
Global.edtImage = rotatedBMP;
break;
case ExifInterface.ORIENTATION_ROTATE_180:

mtx.postRotate(180);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_Profile_pic.setImageBitmap(rotatedBMP);
Global.edtImage = rotatedBMP;
break;
case ExifInterface.ORIENTATION_ROTATE_90:

mtx.postRotate(90);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_Profile_pic.setImageBitmap(rotatedBMP);
Global.edtImage = rotatedBMP;
break;
case ExifInterface.ORIENTATION_NORMAL:

mtx.postRotate(0);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_Profile_pic.setImageBitmap(rotatedBMP);
Global.edtImage = rotatedBMP;
break;
default:
mtx.postRotate(0);
rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), mtx, true);
if (rotatedBMP != bitmap)
bitmap.recycle();
iv_Profile_pic.setImageBitmap(rotatedBMP);
// img_profilepic.setImageBitmap(BitmapFactory
// .decodeFile(mCurrentPhotoPath));
Global.edtImage = rotatedBMP;

}

Log.i("RotateImage", "Exif orientation: " + orientation);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] data = stream.toByteArray();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
// hear store data in parse table.
ParseFile ParseimageFile1 = new ParseFile("IMG_" + timeStamp
+ ".jpg", data);
ParseimageFile1.saveInBackground();
// ParseimageFile1 variable declare at Globle

} catch (Exception e) {
e.printStackTrace();
}

} catch (NullPointerException e) {
e.printStackTrace();
}
}

and this is on activity result.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RESULT_OK) {

if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
Log.d("select pah", "path" + selectedImagePath);
previewCapturedImage();
}

}
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
// display it in image view
selectedImagePath = mediaFile.toString();
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();
}
}

}

now store data at parse table like.
and after store fetch data

ParseObject obj = new ParseObject("ClassName");
obj.put("table colum name", ParseimageFile1);
obj.saveInBackground(new SaveCallback() {

@Override
public void done(ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
// success
} else {
// fail
}
}
});

// now get image from parse table
// in parse table image data type is parseFile

ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Class Name");
query.findInBackground(new FindCallback<ParseObject>() {

@Override
public void done(List<ParseObject> list, ParseException e) {
// TODO Auto-generated method stub
if (e == null) {
// success
for (ParseObject parseObject : list) {
ParseFile image = (ParseFile) parseObject
.get("key_name");
Log.e(key_TAG, "get Image URL " + image.getUrl());
}
} else {
// fail
}

}
});


Related Topics



Leave a reply



Submit