Related
I am working on an app in which I want to get image from gallery or camera and then send it to server using multipart. I am able to send picture from gallery to server but when I tried to send image from camera it shows me failure.
// code for the same
// code fro open camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
// on activity result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA) {
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");
Log.d("TAG", "onActivityResult: "+Uri.fromFile(destination));
filePath = destination.toString();
if (filePath != null) {
try {
execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Image not capturd!", Toast.LENGTH_LONG).show();
}
}
// send to server code
private void execMultipartPost() throws Exception {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
Log.d("TAG", "file new path: " + file.getPath());
Log.d("TAG", "contentType: " + contentType);
RequestBody fileBody = RequestBody.create(MediaType.parse(contentType), file);
final String filename = "file_" + System.currentTimeMillis() / 1000L;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("date", "21-09-2017")
.addFormDataPart("time", "11.56")
.addFormDataPart("description", "hello")
.addFormDataPart("image", filename + ".jpg", fileBody)
.build();
Log.d("TAG", "execMultipartPost: "+requestBody);
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://myexample/api/user/lets_send")
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "nah", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Log.d("TAG", "response of image: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
Try This, it may help
Intent takePhotoIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Date date = new Date();
String timeStamp = new SimpleDateFormat(pictureNameDateFormat, Locale.US).format(date.getTime());
File fileDirectory = new File(Environment.getExternalStorageDirectory() + "/Pictures");
if (fileDirectory.exists()) {
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
new File(Environment.getExternalStorageDirectory() + "/Pictures/picture_"+ timeStamp + ".png")));
takePhotoIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
takePhotoIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (takePhotoIntent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(takeVideoIntent, captureVideoActivityRequestCode);
}
}
private void onCaptureImageResult(Intent data) {
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 (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("path",Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
}
Please use below code to capture image by camera and for pick image from gallery and you can crop also.
First of all please add this dependency in your build.gradle
compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
In your Activity please add this code :
uploadPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSelectImageClick(view);
}
});
/**
* Start pick image activity with chooser.
*/
public void onSelectImageClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AccountSettingActivity.this, new String[]{android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_REQUEST_CAMERA);
} else if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
CropImage.startPickImageActivity(this);
}
}else {
CropImage.startPickImageActivity(this);
}
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(this, data);
startCropImageActivity(imageUri);
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
fileUri = result.getUri();
userImage.setImageURI(result.getUri());
Toast.makeText(this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG).show();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
CropImage.startPickImageActivity(this);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Start crop image activity for the given image.
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
in manifest please add these permissions and ask for run time permissions also ,this may solve your problem ,Your coding is correct those works for me perfectly after adding permission.
Please go trough the following code
try {
if (imageUri != null) {
photo = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
} else {
photo = (Bitmap) data.getExtras().get("data");
}
Uri tempUri = CommonData.getImageUri(getContext(), photo);
uri = tempUri.toString();
String path = CommonData.convertImageUriToFile(tempUri, getActivity());
// new PreprocessImagesTask().execute(path);
showLoader();
new ProcessingImage(this).execute(path);
} catch (Exception e) {
e.printStackTrace();
}
public static Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public static String convertImageUriToFile(Uri imageUri, Activity activity) {
String imgPath = "";
String Path;
try {
Cursor cursor = null;
int imageID = 0;
try {
/* ********** Which columns values want to get ****** */
String[] proj = {
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION
};
cursor = activity.getContentResolver().query(
imageUri, // Get data for specific image URI
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null // Order-by clause (ascending by name)
);
int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
int size = cursor.getCount();
/* ****** If size is 0, there are no images on the SD Card. **** */
if (size == 0) {
// imageDetails.setText("No Image");
} else {
int thumbID = 0;
if (cursor.moveToFirst()) {
Path = cursor.getString(file_ColumnIndex);
//String orientation = cursor.getString(orientation_ColumnIndex);
String CapturedImageDetails = " CapturedImageDetails : \n\n"
+ " ImageID :" + imageID + "\n"
+ " ThumbID :" + thumbID + "\n"
+ " Path :" + Path + "\n";
showLog("CapturedImageDetails", CapturedImageDetails);
imgPath = Path;
// Show Captured Image detail on view
// imageDetails.setText(CapturedImageDetails);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return "" + imgPath;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return "";
}
}
Give a try!
private static final int REQUEST_IMAGE = 100;
private static final String TAG = "MainActivity";
TextView imgPath;
ImageView picture;
File destination;
String imagePath;
//onCreate
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
startActivityForResult(intent, REQUEST_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imagePath = destination.getAbsolutePath();//get your path
imgPath.setText(imagePath);
Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
picture.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else{
imgPath.setText("Request cancelled");
}
}
i want to upload Image in Same Size choosed From Gallary.i.Uploaded to the server ..But Image is uploaded On Server like Compressed....like This Image Below
i want to upload Image in Same Size ...or how to set Cropped Intent In This Methode
here Is My Code To Adjust Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 123987:
if (resultCode == RESULT_OK) {
try {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
Log.d("selectedImagePath", "selectedImagePath = " + selectedImagePath);
ParseImage _ParseImage = new ParseImage();
_ParseImage.activityContext = this;
_ParseImage.execute(selectedImagePath);
} catch (Exception e) {
// TODO: handle exception
}
}
break;
case 1234:
if (resultCode == RESULT_OK) {
try {
final_bitmap = null;
String realPath = Environment.getExternalStorageDirectory() + "/" + fileName;
selectedImagePath = realPath;
new BitmapFactory();
Bitmap btmp = setBitmap(selectedImagePath);
/*String path = selectedImagePath.toLowerCase();
if (path.contains("dcim") && path.contains("camera")) {
btmp = RotateBitmap(btmp, 90);
}*/
int o_width = btmp.getWidth();
int o_height = btmp.getHeight();
// w=1840, h=3264
float large_image_ratio = 300.00f;
//Log.d("orignal_image", "orignal_image = " + o_width + " , " + o_height);
if (o_width > o_height) {
if (o_width >= large_image_ratio) {
float temp_w = (float)o_width/(float)large_image_ratio;
//int temp_h = o_height/large_image_ratio;
//Log.d("temp_w", "temp_w = " + temp_w);
int scales_width = (int) large_image_ratio;
int scales_height = (int) Math.round(o_height/temp_w);
//Log.d("scale_image-if", "scale_image-if = " + scales_width + " , " + scales_height);
final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);
} else {
final_bitmap = btmp;
}
} else {
if (o_height >= large_image_ratio) {
//int temp_w = o_width/large_image_ratio;
float temp_h = (float)o_height/(float)large_image_ratio;
//Log.d("temp_h", "temp_h = " + temp_h);
int scales_width = (int) Math.round(o_width/temp_h);
int scales_height = (int) large_image_ratio;
//Log.d("scale_image-else", "scale_image-else = " + scales_width + " , " + scales_height);
final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);
} else {
final_bitmap = btmp;
}
}
img.setImageBitmap(final_bitmap);
Image_into_Byte(final_bitmap);
img.setVisibility(View.VISIBLE);
btn_upload.setEnabled(true);
} catch (Exception e) {
// TODO: handle exception
}
}
break;
}
}
public class ParseImage extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
protected Context activityContext;
#Override
protected void onPreExecute() {
try {
final_bitmap = null;
this.dialog = new ProgressDialog(activityContext, AlertDialog.THEME_HOLO_LIGHT);
//this.dialog.setTitle(title);
this.dialog.setMessage("Loading Image");
this.dialog.setCanceledOnTouchOutside(false);
this.dialog.show();
} catch (Exception e) {
// TODO: handle exception
}
}
protected String doInBackground(String... image_path) {
try {
new BitmapFactory();
Bitmap btmp = setBitmap(selectedImagePath);
/*String path = selectedImagePath.toLowerCase();
if (path.contains("dcim") && path.contains("camera")) {
btmp = RotateBitmap(btmp, 90);
}*/
int o_width = btmp.getWidth();
int o_height = btmp.getHeight();
// w=1840, h=3264
float large_image_ratio = 300.00f;
//Log.d("orignal_image", "orignal_image = " + o_width + " , " + o_height);
if (o_width > o_height) {
if (o_width >= large_image_ratio) {
float temp_w = (float)o_width/(float)large_image_ratio;
//int temp_h = o_height/large_image_ratio;
//Log.d("temp_w", "temp_w = " + temp_w);
int scales_width = (int) large_image_ratio;
int scales_height = (int) Math.round(o_height/temp_w);
//Log.d("scale_image-if", "scale_image-if = " + scales_width + " , " + scales_height);
final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);
} else {
final_bitmap = btmp;
}
} else {
if (o_height >= large_image_ratio) {
//float temp_w = o_width/large_image_ratio;
float temp_h = (float)o_height/(float)large_image_ratio;
//Log.d("temp_h", "temp_h = " + temp_h);
int scales_width = (int) Math.round(o_width/temp_h);
int scales_height = (int) Math.round(o_width/temp_h);
//Log.d("scale_image-else", "scale_image-else = " + scales_width + " , " + scales_height);
final_bitmap = Bitmap.createScaledBitmap(btmp, scales_width, scales_height, true);
} else {
final_bitmap = btmp;
}
}
} catch (Exception e) {
// TODO: handle exception
}
return "complete";
}
#Override
protected void onPostExecute(String result) {
try {
this.dialog.cancel();
SaveBitmap(final_bitmap);
// final_bitmap
img.setImageBitmap(final_bitmap);
Image_into_Byte(final_bitmap);
btn_upload.setEnabled(true);
} catch (Exception e) {
// TODO: handle exception
}
}
}
// crop intent function
public void cropCapturedImage(Uri picUri){
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
//indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 2);
}
get uri from gallery selected image
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
use this function when get image from gallery and camera :-
// camera on activityresult
cropCapturedImage(Uri.fromFile(file));
// gallery
cropCapturedImage(Uri.fromFile(getRealPathFromURI(data.getData())));
You should make Base64 encoded string of Bitmap and send this image string to server via NameValuePair with url. Use AsyncTask<...> for uploading image like for example:
private class ImgUploadingTask extends AsyncTask<String, Void, String>
{
//do your stuff onPreExecute()
#Override
protected String doInBackground(String... params)
{
try
{
String imageDataString = null;
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(server_url);
List<NameValuePair> list = new ArrayList<NameValuePair>();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
imageDataString = Base64.encodeToString(data, Base64.DEFAULT);
list.add(new BasicNameValuePair("image", imageDataString));
post.setEntity(new UrlEncodedFormEntity(list));
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
String response = EntityUtils.toString(entity);
Log.d("Response ", response);
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
//do your stuff onPostExecute()
After this you have to set your server side code, accept this Base64 encoded String and decode it on server side to get real image.
Currently I am able to upload an existed image in the sdcard to my server. I'm a total newbie in Android programming world and I was wondering how do I dynamically grab the newly taken image and submit it to the server?
This is what I have so far for my onClick event
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback,
myPictureCallback_RAW, myPictureCallback_JPG);
new Thread(new Runnable() {
public void run() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");
//hard code
String path = mediaStorageDir.getPath() + "/" + "IMG_20000106_124322.jpg";
int response= uploadFile(path);
System.out.println("RES : " + response);
}
}).start();
}});
This is the codes for my camera functions
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
FileOutputStream outStream = null;
try
{
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "nypdImages");
if (!mediaStorageDir.exists())
{
if (!mediaStorageDir.mkdirs())
{
Log.d("nypdImages", "Oops! Failed create " + "nypdImages" + " directory");
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String path = mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg";
outStream = new FileOutputStream(String.format(path, System.currentTimeMillis()));
outStream.write(arg0);
outStream.close();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
Toast.makeText(getApplicationContext(), "Image Saved", Toast.LENGTH_SHORT).show();
//VuzixCamera.super.onBackPressed();
}
camera.startPreview();
}};
Hope this answer will help you.
Take A new Picture Code:
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
public class CameraUtil extends Activity {
private final static int REQUEST_TAKE_PHOTO=200;
private final String TAG = "Camera";
String mCurrentPhotoPath;
String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(! isDeviceSupportCamera()){
Log.e(TAG,"Camera Not Supported");
Intent returnFromCameraIntent = new Intent();
setResult(RESULT_CANCELED,returnFromCameraIntent);
finish();
}
else{
dispatchTakePictureIntent();
}
}
private void dispatchTakePictureIntent() {
Log.i(TAG,"Dispatch Take Picture Intent");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try{
photoFile = createImageFile();
}catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
Log.i(TAG,"Error occurred while creating the File");
}
// Continue only if the File was successfully created
if (photoFile != null) {
// fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG,"On Activity Result");
File file= new File(path);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK && path!=null && file.length()>0) {
Intent returnFromCameraIntent = new Intent();
returnFromCameraIntent.putExtra("picturePath",path);
setResult(RESULT_OK,returnFromCameraIntent);
finish();
Log.i(TAG,"Camera Closed");
}else{
Log.i(TAG,"On Result CANCEL");
// cancelled Image capture
try{
/*delete Temperory created file*/
file.delete();
}catch(Exception e){
e.printStackTrace();
}
Intent returnFromCameraIntent = new Intent();
setResult(RESULT_CANCELED,returnFromCameraIntent);
finish();
Log.i(TAG,"Image Capture Cancelled");
}
galleryAddPic();
}
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
String imageFileName = "CAMERA_" + timeStamp + "_WA0001";
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "MyApp"+ File.separator);
if(!root.exists()){
root.mkdirs();
}
// File storageDir = Environment.getExternalStoragePublicDirectory(
// Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
root /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
path=""+image.getAbsolutePath();
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private boolean isDeviceSupportCamera() {
if (getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
}
Choose Existing Picture Code:
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
public class GalleryUtil extends Activity{
private final static int RESULT_LOAD_GALLERY=100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String TAG = "Gallery_Image";
String mCurrentPhotoPath;
File photoFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_GALLERY);
}catch(Exception e){
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i(TAG,"On Activity Result");
if (requestCode == RESULT_LOAD_GALLERY && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Intent returnFromGalleryIntent = new Intent();
returnFromGalleryIntent.putExtra("picturePath",picturePath);
setResult(RESULT_OK,returnFromGalleryIntent);
finish();
}else{
Log.i(TAG,"Image Capture Cancelled");
Intent returnFromGalleryIntent = new Intent();
setResult(RESULT_CANCELED,returnFromGalleryIntent);
finish();
}
}
}
Convert Image to Base64 String:
public class Base64Utils {
private static final String TAG = "Base64Utils";
private String picturePath;
private String base64;
public Base64Utils(String picturePath) {
this.picturePath = picturePath;
}
public String getPicturePath() {
return picturePath;
}
public void setPicturePath(String picturePath) {
this.picturePath = picturePath;
}
public String getBase64() {
FileInputStream fis11=null;
try {
fis11 = new FileInputStream(picturePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ByteArrayOutputStream bos11 = new ByteArrayOutputStream();
byte[] buf = new byte[8096];
try {
for (int readNum; (readNum = fis11.read(buf)) != -1;) {
bos11.write(buf, 0, readNum);
}
} catch (IOException ex) {
ex.printStackTrace();
}
bytes = bos11.toByteArray();
base64 = Base64.encodeToString(bytes, Base64.DEFAULT);
return base64;
}
public void setBase64(String base64) {
this.base64 = base64;
}
}
Main Activity Code: Choose or Take Picture, convert it to base64 string and Send Base64 String to Server.
public class CapatureImage extends Activity implements View.OnClickListener {
private final String TAG = "CapatureImage";
String picturePath;
String base64 = null,
private ImageButton image;
// for popup
private PopupWindow pop;
private final int GALLERY_ACTIVITY_CODE = 200;
private final int CAMERA_ACTIVITY_CODE = 300;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.CapatureImage);
configureComponent();
}
private void configureComponent() {
image = (ImageButton) findViewById(R.id.image);
image.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.image:
initiatePopupWindow();
break;
case R.id.button_camera_dialog:
Intent camera_Intent = new Intent(this.getApplicationContext(),
CameraUtil.class);
pop.dismiss();
this.startActivityForResult(camera_Intent, CAMERA_ACTIVITY_CODE);
break;
case R.id.button_gallery_dialog:
Intent gallery_Intent = new Intent(this.getApplicationContext(),
GalleryUtil.class);
pop.dismiss();
this.startActivityForResult(gallery_Intent, GALLERY_ACTIVITY_CODE);
break;
case R.id.button_cancel_dialog:
pop.dismiss();
break;
case R.id.button_remove_dialog:
Log.i(TAG, "Remove Picture");
image.setImageResource(R.drawable.icon_781q);
picturePath=null;
pop.dismiss();
break;
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == GALLERY_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
picturePath = data.getStringExtra("picturePath");
base64 = new Base64Utils(picturePath).getBase64();
//send this base64 string to server
}
if (resultCode == RESULT_CANCELED) {
// Write your code if there's no result
}
}
if (requestCode == CAMERA_ACTIVITY_CODE) {
if (resultCode == RESULT_OK) {
// Log.i("Camera_Activity", data.toString());
picturePath = data.getStringExtra("picturePath");
base64 = new Base64Utils(picturePath).getBase64(); //send this base64 to server
}
if (resultCode == RESULT_CANCELED) {
// Write your code if there's no result
}
}
}// onActivityResult
public void initiatePopupWindow() {
try {
// We need to get the instance of the LayoutInflater
LayoutInflater inflater = (LayoutInflater) EngineerStatus_Update.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialoge_choosephoto,
(ViewGroup) findViewById(R.id.photo_popup));
if (picturePath != null && !picturePath.isEmpty()) {
Log.i(TAG, "Image Exist..Add Remove Button");
remove = (Button) layout
.findViewById(R.id.button_remove_dialog);
remove.setOnClickListener(this);
remove.setVisibility(View.VISIBLE);
pop = new PopupWindow(layout,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
} else {
Log.i(TAG, "No Image..remove Remove Button");
remove = (Button) layout
.findViewById(R.id.button_remove_dialog);
remove.setOnClickListener(this);
remove.setVisibility(View.GONE);
pop = new PopupWindow(layout,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true);
}
// component for popup
gallery = (Button) layout.findViewById(R.id.button_gallery_dialog);
gallery.setOnClickListener(this);
camera = (Button) layout.findViewById(R.id.button_camera_dialog);
camera.setOnClickListener(this);
cancel = (Button) layout.findViewById(R.id.button_cancel_dialog);
cancel.setOnClickListener(this);
pop.showAtLocation(layout, Gravity.CENTER, 0, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
void displayImage(String path) {
File imgFile = new File(path);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
image.setScaleType(ScaleType.CENTER_CROP);
}
}
}
there is two classes upload and main_activity.And i here put it's xml file
public class MainActivity extends Activity {
final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
private static final String TAG = "CaptureImage.java";
public static ImageView showImg = null;
static String uploadFilePath = " ";
static String Path;
static int delete_image_id = 0;
static TextView imageDetails = null;
// FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(CaptureImage.this);
static Cursor cursor = null;
public ProgressDialog dialog_upload = null;
public String s_name;
public String s_Adress;
int serverResponseCode = 0;
TextView shift_display;
Uri imageUri = null;
OnClickListener oclBtnOk = new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("VALUES", "It is Working");
String fileName = "Camera_Example.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
};
MainActivity CameraActivity = null;
Upload upload;
Button outlet_names_show;
double latitude;
double longitude;
OnClickListener oclBtnOk3 = new OnClickListener() {
#Override
public void onClick(View v) {
if (showImg.getDrawable() == null) {
Toast.makeText(MainActivity.this, " Picture was not captured ",
Toast.LENGTH_SHORT).show();
} else {
upload_prescription();
// CallSummery.flag_bt_merchan=true;
}
}
};
private Button buttonback;
/**
* ********* Convert Image Uri path to physical path *************
*/
public static String convertImageUriToFile(Uri imageUri, Activity activity) {
int imageID = 0;
try {
/*********** Which columns values want to get *******/
String[] proj = {MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION};
cursor = activity.getContentResolver().query(imageUri, proj, null,
null, null);
// Get Query Data
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
int file_ColumnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// int orientation_ColumnIndex = cursor.
// getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
int size = cursor.getCount();
/******* If size is 0, there are no images on the SD Card. *****/
if (size == 0) {
// imageDetails.setText("No Image");
} else {
if (cursor.moveToFirst()) {
imageID = cursor.getInt(columnIndex);
delete_image_id = imageID;
Path = cursor.getString(file_ColumnIndex);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
// Return Captured Image ImageID ( By this ImageID Image will load from
// sdcard )
return "" + imageID;
}
protected void onCreate(Bundle savedInstanceState) {
MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraActivity = this;
showImg = (ImageView) findViewById(R.id.showImg);
upload = new Upload(MainActivity.this);
final Button photo = (Button) findViewById(R.id.photo);
final Button upload = (Button) findViewById(R.id.upload);
photo.setOnClickListener(oclBtnOk);
upload.setOnClickListener(oclBtnOk3);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (imageUri != null) {
outState.putString("cameraImageUri", imageUri.toString());
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey("cameraImageUri")) {
imageUri = Uri
.parse(savedInstanceState.getString("cameraImageUri"));
}
}
public void upload_prescription() {
dialog_upload = ProgressDialog.show(MainActivity.this, "",
"Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
}
});
createDirectoryIfNeeded();
upload.uploadFile(uploadFilePath);
}
}).start();
}
private void createDirectoryIfNeeded() {
File direct = new File(Environment.getExternalStorageDirectory()
+ "/Capturetemp");
if (!direct.exists()) {
if (direct.mkdir()) {
// directory is created;
}
}
}
public void copy(String lo, String lan) throws JSONException {
String sdCard = Environment.getExternalStorageDirectory().toString();
Random ran = new Random();
uploadFilePath = sdCard + "/Capturetemp/" + ran.toString() + ".jpg";
File sourceLocation = new File(Path);
File targetLocation = new File(uploadFilePath);
Log.v(TAG, "sourceLocation: " + sourceLocation);
Log.v(TAG, "targetLocation: " + targetLocation);
try {
// 1 = move the file, 2 = copy the file
int actionChoice = 2;
// moving the file to another directory
if (actionChoice == 1) {
if (sourceLocation.renameTo(targetLocation)) {
Log.v(TAG, "Move file successful.");
} else {
Log.v(TAG, "Move file failed.");
}
}
// we will copy the file
else {
// make sure the target file exists
if (sourceLocation.exists()) {
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.v(TAG, "Copy file successful.");
} else {
Log.v(TAG, "Copy file failed. Source file missing.");
}
}
} catch (NullPointerException e) {
// e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
/*********** Load Captured Image And Data Start ***************/
String imageId = convertImageUriToFile(imageUri, CameraActivity);
// Create and excecute AsyncTask to load capture image
new LoadImagesFromSDCard(MainActivity.this).execute(""
+ imageId);
/*********** Load Captured Image And Data End ****************/
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, " Picture was not taken ",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, " Picture was not taken ",
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onBackPressed() {
}
public class LoadImagesFromSDCard extends AsyncTask<String, Void, Void> {
Context context;
Bitmap mBitmap;
private ProgressDialog loadingdailog;
public LoadImagesFromSDCard(MainActivity context) {
this.context = context;
}
#Override
protected void onPreExecute() {
loadingdailog = new ProgressDialog(context);
loadingdailog.setMessage("Loading Image.....");
loadingdailog.show();
}
// Call after onPreExecute method
#Override
protected Void doInBackground(String... urls) {
Bitmap bitmap = null;
Bitmap newBitmap = null;
Uri uri = null;
try {
uri = Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ""
+ urls[0]);
/************** Decode an input stream into a bitmap. *********/
bitmap = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(uri));
if (bitmap != null) {
/********* Creates a new bitmap, scaled from an existing bitmap. ***********/
newBitmap = Bitmap.createScaledBitmap(bitmap, 350, 350,
true);
// SaveIamge(newBitmap);
bitmap.recycle();
if (newBitmap != null) {
mBitmap = newBitmap;
}
}
} catch (IOException e) {
// Error fetching image, try to recover
/********* Cancel execution of this task. **********/
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
if (loadingdailog.isShowing() && loadingdailog != null) {
loadingdailog.dismiss();
loadingdailog = null;
}
if (mBitmap != null) {
showImg.setImageBitmap(mBitmap);
}
}
}
}
upload class
public class Upload {
protected MainActivity context;
ProgressDialog dialog = null;
int serverResponseCode = 0;
String uploadFilePath = null;
String uploadFileName = null;
String msg = null;
String upLoadServerUri = "http://fileuploadpath";
public Upload(MainActivity context) {
this.context = context;
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
return 0;
} else {
try {
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("photo", fileName);
// conn.setRequestProperty("session_id","13");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"photo\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
try {
readStream(conn.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
if (serverResponseCode == 200) {
context.runOnUiThread(new Runnable() {
public void run() {
context.dialog_upload.dismiss();
Toast.makeText(context, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
fileInputStream.close();
} catch (MalformedURLException ex) {
// Toast.makeText(context, "File Upload Not Complete.",
// Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
// context.dialog.dismiss();
e.printStackTrace();
// Toast.makeText(context, "File Upload Not Complete.",
// Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
// context.dialog.dismiss();
return serverResponseCode;
}
}
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
Log.e("tag", line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical"
android:padding="10dp"
android:weightSum="1" >
<ImageView
android:id="#+id/showImg"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:contentDescription="bla bla" />
<Button
android:id="#+id/photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Capture Image"
android:textSize="26sp" />
<Button
android:id="#+id/upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Upload Photo"
android:textSize="26sp" />
</LinearLayout>
for image uri you should paste your file upload path
i am getting error in log cat
{Response: responseCode: 400, graphObject: null, error: {HttpStatus:
400, errorCode: 353, errorType: OAuthException, errorMessage: (#353)
Missing video file}, isFromCache:false}
using below Method
private void postVideo() {
try {
File file = new File(videoPath);
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle(1);
parameters.putParcelable(file.getName(), descriptor);
new Request(Session.getActiveSession(), "me/videos", parameters, HttpMethod.POST, new Request.Callback() {
#Override
public void onCompleted(Response response) {
Constants.showLog(TAG, "In Response " + response.getGraphObject().getProperty("id"));
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
Constants.showLog(TAG, "In Response id " + postId);
} catch (JSONException e) {
Constants.showLog(TAG,"JSON error "+ e.getMessage());
}
}
}).executeAsync();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
please help
I see you are using the Android SDK 3.0, and with that we included a simple way to upload videos. Here is my code that I use to upload videos to Facebook:
Request.Callback callback5 = new Request.Callback() {
public void onCompleted(Response response) {
// response will have an id if successful
}
};
File tempFile;
try {
tempFile = Util.createTempFileFromAsset(getApplicationContext(), "video.mp4");
Request request5 = Request.newUploadVideoRequest(session,
tempFile, callback5);
RequestAsyncTask task5 = new RequestAsyncTask(request5);
task5.execute();
} catch (IOException e) {
Log.e(Util.TAG, "failed to create temp file");
e.printStackTrace();
}
and the code for createTempFileFromAsset:
public static File createTempFileFromAsset(Context context, String assetPath)
throws IOException {
InputStream inputStream = null;
FileOutputStream outStream = null;
try {
AssetManager assets = context.getResources().getAssets();
inputStream = assets.open(assetPath);
File outputDir = context.getCacheDir(); // context being the
// Activity pointer
File outputFile = File.createTempFile("prefix", assetPath,
outputDir);
outStream = new FileOutputStream(outputFile);
final int bufferSize = 1024 * 2;
byte[] buffer = new byte[bufferSize];
int n = 0;
while ((n = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
}
return outputFile;
} finally {
Utility.closeQuietly(outStream);
Utility.closeQuietly(inputStream);
}
}
pick the file onActivityResult....
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
SubmitPost.this.file = new File(SubmitPost.this.file, picturePath);
// MimeTypeMap mime = MimeTypeMap.getSingleton();
// String type = mime.getMimeTypeFromExtension(ext);
cursor.close();
}
break;
}
and use
if (!postParams.containsKey(MIGRATION_BUNDLE_PARAM)) {
postParams.putString(MIGRATION_BUNDLE_PARAM, FbSdkVersion.MIGRATION_BUNDLE);
}
after
ParcelFileDescriptor descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
Bundle parameters = new Bundle(1);
parameters.putParcelable(file.getName(), descriptor);
Can we upload videos from an Android device's SD Card to a Facebook account via the Facebook SDK?
If so, what are some simple examples?
Yes, it is possible! After two days of trying and researching, I was able to do it.
Here's the code:
byte[] data = null;
String dataPath = "/mnt/sdcard/KaraokeVideos/myvideo.3gp";
String dataMsg = "Your video description here.";
Bundle param;
facebook = new Facebook(FB_APP_ID);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
InputStream is = null;
try {
is = new FileInputStream(dataPath);
data = readBytes(is);
param = new Bundle();
param.putString("message", dataMsg);
param.putString("filename", dataName);
param.putByteArray("video", data);
mAsyncRunner.request("me/videos", param, "POST", new fbRequestListener(), null);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
where fbRequestListener() is an implementation of AsyncFacebookRunner.RequestListener() and readBytes() is a function of converting your video file to byte[]. The dataName string should include a valid file extension (3gp, mp4, etc.). The code is as follows:
public byte[] readBytes(InputStream inputStream) throws IOException {
// This dynamically extends to take the bytes you read.
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// This is storage overwritten on each iteration with bytes.
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// We need to know how may bytes were read to write them to the byteBuffer.
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// And then we can return your byte array.
return byteBuffer.toByteArray();
}
I got this function from this answer.
Of course, you need to have the latest Facebook SDK, but we need to apply this patch to fix the {"error":{"type":"OAuthException","message":"(#352) Video file format is not supported"}} string response error.
And that's it! I hope this helps!
With the release of new facebook SDK 3.5, video uploading has been made easier.
If you are using sdk 3.5 or above here is the code for uploading video to facebook
//Path to the video, Ex: path = Environment.getExternalStorageDirectory() + File.separator + "myVideo.mp4";
String path;
//get the current active facebook session
Session session = Session.getActiveSession();
//If the session is open
if(session.isOpened()) {
//Get the list of permissions associated with the session
List<String> permissions = session.getPermissions();
//if the session does not have video_upload permission
if(!permissions.contains("video_upload")) {
//Get the permission from user to upload the video to facebook
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, Arrays.asList("video_upload"));
session.requestNewReadPermissions(newPermissionsRequest);
}
//Create a new file for the video
File file = new File(path);
try {
//create a new request to upload video to the facebook
Request videoRequest = Request.newUploadVideoRequest(session, file, new Request.Callback() {
#Override
public void onCompleted(Response response) {
if(response.getError()==null)
{
Toast.makeText(MainActivity.this, "video shared successfully", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, response.getError().getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
});
//Execute the request in a separate thread
videoRequest.executeAsync();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//Session is not open
else {
Toast.makeText(getApplicationContext(), "Please login to facebook first", Toast.LENGTH_SHORT).show();
}
After patching Util file, did not get result.
I faced problem mentioned by softy.
I tried with this in android... Now works successfully.. video displayed on my wall after sometime (within 1 min).. (May be, facebook was refreshing data..)
String path="\mnt\sdcard\test.mp4";
if (new File(path).exists()) {
try {
byte[] data = null;
String dataPath = new File(path).getAbsolutePath();
Log.e("", dataPath);
String dataMsg = "It is the short movie created";
Bundle param;
InputStream is = null;
try {
is = new FileInputStream(dataPath);
data = readBytes(is);
param = new Bundle();
// param.putString("filename", "" + new
// File(path).getName());
// param.putString("mimeType", "video/mp4");
param.putString("message", dataMsg);
param.putString("title", "title");
param.putString("contentType", "video/quicktime");
param.putByteArray("video.mov", data);
Utility.mAsyncRunner.request("me/videos", param, "POST",
new FBRequestListener(), null);
Toast.makeText(getContext(), "Uploading...",
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getContext(), "No videos found in these dates",
Toast.LENGTH_SHORT).show();
}
FBRequestListener.java
public class FBRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
Log.e("response", response);
// Log.e("state", state.toString());
}
#Override
public void onIOException(IOException e, Object state) {
Log.e("", "onIOException");
e.printStackTrace();
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.e("", "onFileNotFoundException");
e.printStackTrace();
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.e("", "onMalformedURLException");
e.printStackTrace();
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.e("", "onFacebookError");
e.printStackTrace();
}
}
In release of new facebook SDK, there are some changes in video uploading to facebook page or wall.
Here is code i have used for uploading video on Facebook page or facebook wall.
Your onActivityResult() method should be like this
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_VIDEO && resultCode == Activity.RESULT_OK){
String selectedVideoFilePath = GetFilePathFromDevice.getPath(this, data.getData());
final byte[] datas = readBytes(selectedVideoFilePath);
PostVideo(datas, selectedVideoFilePath);
}
}
Here is all method used in onActivityResult().
public byte[] readBytes(String dataPath) throws IOException {
InputStream inputStream = new FileInputStream(dataPath);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
public void PostVideo(byte[] VideoBytes, String filePath) {
String url;
url = "/me/videos";
AccessToken token = AccessToken.getCurrentAccessToken();
if (token != null) {
Bundle param = new Bundle();
param.putByteArray("video." + getFileExt(filePath), VideoBytes);
param.putString("description", "sample video");
new GraphRequest(token,url, param, HttpMethod.POST, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("New Post", "Res =" + response.toString());
dialog.dismiss();
if (response != null && response.getJSONObject() != null && response.getJSONObject().has("id")) {
Log.e("New Post", "Success");
Toast.makeText(NewPostActivity.this, "Video posted successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(NewPostActivity.this, "Error in posting Video.", Toast.LENGTH_SHORT).show();
}
setResult(Activity.RESULT_OK, new Intent());
finish();
}
}).executeAsync();
}
}
public static String getFileExt(String fileName) {
return fileName.substring((fileName.lastIndexOf(".") + 1), fileName.length());
}
Here is GetFilePathFromDevice class used in onActivityResult() for getting file path from URI.
#SuppressLint("NewApi")
public final class GetFilePathFromDevice {
/**
* Get file path from URI
*
* #param context context of Activity
* #param uri uri of file
* #return path of given URI
*/
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}