I am attempting to use this reference:
https://www.parse.com/docs/android/guide#files
To understand how to get a file taken by the camera and save it to Parse. I have this code:
private File getOutputMediaFile(int type) {
// External sdcard location
String appName = CameraActivity.this.getString(R.string.app_name);
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
appName);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(appName, "Oops! Failed create "
+ appName + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
final File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
final ParseFile photoFile;
byte[] data = mediaFile.getBytes();
// Save the scaled image to Parse
photoFile = new ParseFile("profile_photo.jpg", data);
But I get the error: cannot resolve getBytes.
Do I need to convert this file to something else before using getBytes? Is it in the wrong format?
File haven't method getBytes(), you need to convert it to byte array, how is answered here : File to byte[] in Java
Here is my solution, based on this: http://www.mkyong.com/java/how-to-convert-file-into-an-array-of-bytes/:
private File getOutputMediaFile(int type) {
// External sdcard location
String appName = CameraActivity.this.getString(R.string.app_name);
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
appName);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(appName, "Oops! Failed create "
+ appName + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
final File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
final ParseFile photoFile;
FileInputStream fileInputStream=null;
byte[] bFile = new byte[(int) mediaFile.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(mediaFile);
fileInputStream.read(bFile);
fileInputStream.close();
for (int i = 0; i < bFile.length; i++) {
System.out.print((char)bFile[i]);
}
System.out.println("Done");
}catch(Exception e) {
e.printStackTrace();
}
// Save the image to Parse
photoFile = new ParseFile("profile_photo.jpg", bFile);
photoFile.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e != null) {
} else {
addPhotoToProfile(photoFile);
}
}
});
return mediaFile;
}
private void addPhotoToProfile(ParseFile photoFile) {
mCurrentUser.getCurrentUser();
mCurrentUser.put("ProfilePhoto", photoFile);
}
Related
After recording the video
mMediaRecorder
.setOutPutFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());
create the media file
private static File getOutputMediaFile(int type) {
File mediaStorageDir = newFile(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "Pitch");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("Pitch", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_" + timeStamp + ".jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
I sent the video path with an intent to my video play activity to display the video
public void RecieveUri() {
Intent intent = new Intent(this,VideoPlayBackActivity.class);
vidPath = getOutputMediaFile(MEDIA_TYPE_VIDEO);
vidP = vidPath.getAbsolutePath();
intent.putExtra(EXTRA_MESSAGE,vidP);
startActivity(intent);
}
I received the file path checked if it was not empty
Intent intent = getIntent();
vidPATH = intent.getStringExtra(CameraActivity.EXTRA_MESSAGE);
if(vidPATH.isEmpty()){
Toast.makeText(this,"Error",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this,"Path: "+vidPATH,Toast.LENGTH_SHORT).show();
}
Then i tried to play the video using media player
try{
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(vidPATH);
mMediaPlayer.setSurface(surface);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepareAsync();
but it does not play the screen stays black and the log cat says
W/System.err: java.io.IOException: setDataSource failed.
I am using this code right now but its destroy image quality.
I have issue regarding blur image
if (requestCode == IMAGE_REQUEST_CODE) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// kkkk(data.getData());
picture = (Bitmap) data.getExtras().get("data");//this
// I pass bitmap to function to get watermark
result = mark(picture , sh.getString("BARCODE", null), 10, 50,R.color.colorPrimaryDark, 200, 30, false);
// now i need a file to upload image on dropbox
file = storeImage(result);
}
// here is my function
private File storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d("",
"Error creating media file, check storage permissions: ");// e.getMessage());
return null;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG,55, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.d("", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("", "Error accessing file: " + e.getMessage());
}
return pictureFile;
}
private File getOutputMediaFile() {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
File mediaFile;
increase++;
String mImageName = sh.getString("BARCODE", null) + "_" + timeStamp + ".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
</i>
}
This is the method I use to store images.
private String saveImage (Context context, String name, Bitmap image){
ContextWrapper cw = new ContextWrapper(context);
File dirImages = cw.getDir(Imagenes, Context.MODE_PRIVATE);
File myPath = new File(dirImages, name + .png);
FileOutputStream fos = null;
try{
fos = new FileOutputStream(myPath);
image.compress(Bitmap.CompressFormat.JPEG, 10, fos);
fos.flush();
}catch (FileNotFoundException ex){
ex.printStackTrace();
}catch (IOException ex){
ex.printStackTrace();
}
return myPath.getAbsolutePath();
}
How do I adapt to store audio and video?
Try using this snippet of code:
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
public static final int MEDIA_TYPE_AUDIO = 3;
/** Create a File for saving an image, video or audio */
public static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "App");
// This locat ion works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
android.util.Log.d("log", "failed to create directory");
return null;
}
}
// Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ "PhotoTemp" + ".png");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ "VideoTemp" + ".mp4");
}
else if(type == MEDIA_TYPE_AUDIO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"AUD_"+ "AudioTemp" + ".mp3");
}
else {
return null;
}
return mediaFile;
}
And then:
File mediaFile = getOutputMediaFile(MEDIA_TYPE_AUDIO);
if (mediaFile == null) {
android.util.Log.d("log", "Error creating media file, check storage permissions");
return null;
}
FileOutputStream fos = new FileOutputStream(mediaFile);
fos.write(data); //where data is byte[]
fos.close();
While downloding from server which you probably do in chunks in a byte buffer, immediately write every chunk to file
I am attempting to save a photo Parse. The photo is taking, and I can preview it, however, I am not seeing the file on the Parse backend.
Here is my code:
* returning image / video
*/
private File getOutputMediaFile(int type) {
// External sdcard location
String appName = CameraActivity.this.getString(R.string.app_name);
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
appName);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(appName, "Oops! Failed create "
+ appName + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
final File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
final ParseFile photoFile;
FileInputStream fileInputStream=null;
byte[] bFile = new byte[(int) mediaFile.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(mediaFile);
fileInputStream.read(bFile);
fileInputStream.close();
for (int i = 0; i < bFile.length; i++) {
System.out.print((char)bFile[i]);
}
System.out.println("Done");
}catch(Exception e) {
e.printStackTrace();
}
// Save the image to Parse
photoFile = new ParseFile("profile_photo.jpg", bFile);
photoFile.saveInBackground();
mCurrentUser.getCurrentUser();
mCurrentUser.put("ProfilePhoto", photoFile);
mCurrentUser.saveInBackground();
return mediaFile;
}
I am using this as a reference: https://www.parse.com/docs/android/guide#files I also realize I need to get the data in byte format. So I am attempting to do that, but may not be doing that correctly.
sample below uses apache httpClient rather than parse.android.SDK.saveInBackground() ... but it may help you with mapping the files bytes
FileInputStream fis = new FileInputStream(mfile);
FileChannel fc = fis.getChannel(); // Get the file's size and then map it into memory
int sz = (int)fc.size();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
data2 = new byte[bb.remaining()];
bb.get(data2);
ByteArrayEntityHC4 reqEntity = new ByteArrayEntityHC4(data2);
httpPost.setEntity(reqEntity);
fis.close();
i am trying to save captured image in portrait mode ...
but not getting click how to do this?
here is my code...
captureImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
camera.takePicture(null, null, mPicture);
}
});
PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
System.out.println("picture file is null");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
// map.compress(Bitmap.CompressFormat.JPEG, 20, fos);
// fos.flush();
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
and the outputmedia ...
private File getOutputMediaFile() {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + "_" + userId + ".jpg");
String imageName = "IMG_" + timeStamp + "_" + userId + ".jpg";
System.out.println("###### image is: " + imageName);
Intent intent = new Intent(this, VideoPlaybackActivity.class);
intent.putExtra("file_name", imageName);
intent.putExtra("data_type", "image");
intent.putExtra("fromClass", "Captured_Image");
intent.putExtra("expiry_time", "5");
intent.putExtra("cameraId", cameraId);
super.startActivity(intent);
finish();
return mediaFile;
}
i am getting image in my directory
but all images are in landscape mode.
so please if any body can help...