Writing and reading file - android

I'm having a problem writing and reading files.
Here goes the code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch(requestCode) {
case INTENT_COUNTRY:
if (data.getExtras().containsKey("country")) {
final String c = data.getStringExtra("country");
Log.d("Profile", "Country: " + c);
txtCountry.setText(c);
}
break;
case PICKER_CAMERA:
Log.d("Profile", "PICKER_CAMERA");
Bitmap bitmapCamera = (Bitmap) data.getExtras().get("data");
Bitmap thumbnailCamera = ThumbnailUtils.extractThumbnail(bitmapCamera, 320, 320);
ByteArrayOutputStream streamCamera = new ByteArrayOutputStream();
thumbnailCamera.compress(Bitmap.CompressFormat.PNG, 100, streamCamera);
byte[] byteArrayCamera = streamCamera.toByteArray();
InputStream isCamera = new ByteArrayInputStream(byteArrayCamera);
uploadPicture(isCamera);
break;
case PICKER_GALLERY:
Log.d("Profile", "PICKER_GALLERY");
Uri imageUri = data.getData();
try {
Bitmap bitmapGallery = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), imageUri);
Bitmap thumbnailGallery = ThumbnailUtils.extractThumbnail(bitmapGallery, 320, 320);
ByteArrayOutputStream streamGallery = new ByteArrayOutputStream();
thumbnailGallery.compress(Bitmap.CompressFormat.PNG, 100, streamGallery);
byte[] byteArrayGallery = streamGallery.toByteArray();
InputStream isGallery = new ByteArrayInputStream(byteArrayGallery);
uploadPicture(isGallery);
} catch(IOException e) {
e.printStackTrace();
}
break;
default:
Log.d("Profile", "Unmanaged request code: " + requestCode);
break;
}
}
}
public void uploadPicture(InputStream is) {
final ProgressDialog progress = new ProgressDialog(getActivity());
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setTitle(getString(R.string.loading));
progress.setMessage(getString(R.string.loading_msg));
progress.show();
/* Upload*/
AppDelegate appDelegate = (AppDelegate) getActivity().getApplication();
appDelegate.setPicture(is, new Callable<Void>() {
#Override
public Void call() throws Exception {
Log.d("Profile", "Upload ok");
progress.dismiss();
return null;
}
}, new Callable<Void>() {
#Override
public Void call() throws Exception {
Log.d("Profile", "Upload failed");
progress.dismiss();
return null;
}
});
}
public void setPictureFile(final InputStream is) {
String filename = "pict.png";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(IOUtils.toByteArray(is));
outputStream.close();
Log.d("Profile", "File stored locally.");
} catch (Exception e) {
e.printStackTrace();
}
}
public Bitmap getPictureFile() {
String filename = "pict.png";
FileInputStream inputStream;
//String filePath = getFilesDir().getAbsolutePath() + "/" + filename;
Bitmap bitmap = null;
try {
inputStream = openFileInput(filename);
BufferedInputStream buf = new BufferedInputStream(inputStream);
bitmap = BitmapFactory.decodeStream(buf);
//Bitmap bitmap = BitmapFactory.decodeFile(filename);
if (bitmap == null) {
Log.d("Profile", "WARNING: bitmap == null");
}
if (inputStream != null) {
inputStream.close();
}
if (buf != null) {
buf.close();
}
} catch(FileNotFoundException e) {
Log.d("Profile", "Picture FILE not found.");
e.printStackTrace();
return null;
} catch (OutOfMemoryError e) {
Log.d("Profile", "Out Of Memory");
} catch(Exception e) {
e.printStackTrace();
}
return bitmap;
}
In console I always have:
WARNING: bitmap == null
The InputStream in the setPictureFile method is not null (upload to a web-services works as expected) and I didn't get any exception in setPictureFile.
On the other hand, when I'm trying to read the file, the bitmap seems to be null, no exception is rising up!
The file I'm trying to read is about 200-300 KB, so it's not big, I'm not running out of memory.
Anyone knows what's going on?

Solved. Using byte[] instead of InputStream everywhere, solved my issue.
public void setPictureFile(final byte[] buffer) {
String filename = "pict.png";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(buffer);
outputStream.close();
Log.d("Profile", "File stored locally.");
} catch (Exception e) {
Log.d("Profile", e.toString());
e.printStackTrace();
}
}
public Bitmap getPictureFile() {
String filename = "pict.png";
FileInputStream inputStream;
// http://stackoverflow.com/questions/11182714/bitmapfactory-example
// http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
//String filePath = getFilesDir().getAbsolutePath() + "/" + filename;
Bitmap bitmap = null;
try {
inputStream = openFileInput(filename);
byte[] reader = new byte[inputStream.available()];
if (inputStream.read(reader)!=-1) {
Log.d("Profile", "Reading from stream...");
}
Log.d("Profile", "Stream length: " + reader.length);
bitmap = BitmapFactory.decodeByteArray(reader, 0, reader.length);
//BufferedInputStream buf = new BufferedInputStream(inputStream);
//bitmap = BitmapFactory.decodeStream(inputStream);
//Bitmap bitmap = BitmapFactory.decodeFile(filename);
if (bitmap == null) {
Log.d("Profile", "WARNING: bitmap == null");
}
inputStream.close();
//if (buf != null) {
// buf.close();
//}
} catch(FileNotFoundException e) {
Log.d("Profile Exception", e.toString());
e.printStackTrace();
} catch (OutOfMemoryError e) {
Log.d("Profile Exception", e.toString());
} catch(Exception e) {
Log.d("Profile Exception", e.toString());
e.printStackTrace();
}
return bitmap;
}

Related

Recover bitmap file from FileOutputStream in a fragment

Im trying to capture image and then for good practice I put bitmap file in the the FileOutputStream how can I recover the bitmap using the filename.
Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK){
if (requestCode == REQUEST_CODE_CAMERA && data != null){
fragment = null;
Bitmap bmp = (Bitmap) data.getExtras().get("data");
String filename = "bitmap.png";
try {
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
assert bmp != null;
bmp.compress(Bitmap.CompressFormat.PNG,100,stream);
stream.close();
bmp.recycle();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.slide_in_left,R.anim.fade_out,R.anim.fade_in,R.anim.slide_out_right);
fragment =FragmentCropper.newInstance(filename);
fragmentTransaction.add(R.id.fragmentContainer,fragment,Constant.BackStackTag.CROP_TAG);
fragmentTransaction.addToBackStack(Constant.BackStackTag.CROP_TAG);
fragmentTransaction.commit();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the Fragment
How to recover the Bitmap using the filename
try {
//FileInputStream stream = getActivity().openFileInput(filename);
//mBitmap = BitmapFactory.decodeStream(stream);
//stream.close();
String path = "path/"+filename;
mBitmap = BitmapUtils.decodeSampledBitmapFromFile(path,500,500);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (mBitmap.isRecycled())
mBitmap.recycle();
mBitmap=null;
}
String path = "path/"+filename;
Change to
String path = getFilesDir().getAbsolutePath() + "/" + filename;

Not able to upload camera captured image on server in android

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));
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();
}
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();
}
}
});
}
});
}
// I am getting onFailure executed while try to upload image from camera.
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
As per comments :
Get image from gallery or camera like this :
File mainFile = null;
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
String partFilename = currentDateFormat();
mainFile = storeCameraPhotoInSDCard(bitmap, partFilename);
public String currentDateFormat() {
String currentTimeStamp = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
currentTimeStamp = dateFormat.format(new Date());
} catch (Exception e) {
e.printStackTrace();
}
return currentTimeStamp;
}
public File storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate) {
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return outputFile;
}
Use mainFile to send in RequestBody and pass like execMultipartPost(File file)

Retrofit 2 download image and save to folder

I need to download image from server and save it to folder, so I am using Retrofit 2.
Problem is that saved images is empty when I look for it in folder and I tried to debug and saw that Bitmap is null.
I do not get why, here is my code:
#GET("images/{userId}/{imageName}")
#Streaming
Call<ResponseBody> downloadImage(#Path("userId") String userId, #Path("imageName") String imageName);
Download image code:
private void downloadImage(final int position) {
String url = "htttp://myserver.com/";
retrofitImage = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
imageApi = retrofitImage.create(BlastApiService.class);
String userId = feedList.get(position).getUserId();
String fileName = feedList.get(position).getFile();
Call<ResponseBody> imageCall = imageApi.downloadImage(userId, fileName );
imageCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccess()){
String fileName = feedList.get(position).getFile();
InputStream is = response.body().byteStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
saveImage1(bitmap, fileName);
} else{
try {
Log.d("TAG", "response error: "+response.errorBody().string().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("TAG", "Image download error: " + t.getLocalizedMessage());
}
});
}
Here is method to save image.
private void saveImage1(Bitmap imageToSave, String fileName) {
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + "/FOLDER_NAME/");
// create this directory if not already created
dir.mkdir();
// create the file in which we will write the contents
File file = new File(dir, fileName);
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
counter++;
// if (counter < feedList.size()) {
//downloadImage(counter);
//} else {
setImage();
//}
} catch (Exception e) {
e.printStackTrace();
}
}
This worked for me:
public static boolean writeResponseBody(ResponseBody body, String path) {
try {
File file = new File(path);
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
//long fileSize = body.contentLength();
//long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(file);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
//fileSizeDownloaded += read;
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
after call this method you can get image from path:
boolean result = writeResponseBody(body, path);
if(result) {
Bitmap bitmap = BitmapFactory.decodeFile(path)
}
private boolean writeResponseBodyToDisk(ResponseBody body, String name) {
try {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/MyApp";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
File futureStudioIconFile = new File(path, name + ".pdf");//am saving pdf file
if (futureStudioIconFile.exists())
futureStudioIconFile.delete();
futureStudioIconFile.createNewFile();
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
}
outputStream.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

Android: IOException BufferedInputStream is closed after download

I've some problems with InputStream after download an image. downloadImages method return an InputStream that i write in a file. But there is an exception in inputStreamToFile method: java.io.IOException: BufferedInputStream is closed. Here the codes:
Download
public static InputStream downloadImages(String imageUrl) {
HttpURLConnection httpConn = null;
String urlBase = imageUrl;
if(D) Log.d(TAG, "downloadImages(): url request: " + urlBase);
try {
URL url = new URL(urlBase);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setConnectTimeout(SystemConstants.TIMEOUT_CONNECTION);
httpConn.setReadTimeout(SystemConstants.SOCKET_CONNECTION);
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
return inputStream;
}
} catch (IOException e) {
Log.w(TAG, "downloadImages(): exception: " + e);
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
} finally {
if(httpConn != null) httpConn.disconnect();
}
return null;
}
From IS to file
public static void inputStreamToFile(InputStream is) {
if(D) Log.d(TAG, "inputStreamToFile() called");
OutputStream outputStream = null;
try {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!Utils.isExternalStorageRemovable() ?
Utils.getExternalCacheDir(App.getContext()).getPath() :
App.getContext().getCacheDir().getPath();
// write the inputStream to a FileOutputStream
outputStream = new FileOutputStream(new File(cachePath + File.separator + "vr"));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
if(D) Log.d(TAG, "read called");
outputStream.write(bytes, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
if(D) Log.d(TAG, "inputStreamToFile(): outputStream is not null");
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Put your logcat.Then only we can identify the errors,bugs,etc

Bitmap.compress always returns null

I am downloading requested image from my server , this image is successfully displayed after downloading but when i try to store the same image on my SD card it returns null.
Here is my code for downloading image and saving it.I am getting null on a call to bitmap.compress()
void saveImage() {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image.png";
File file = new File (myDir, fname);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
message_bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//write the bytes in file
FileOutputStream fo;
try {
fo = new FileOutputStream(file);
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
message_bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}*/
}
static public Bitmap downloadBitmap(String url) {
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.w("ImageDownloader", "Error while retrieving bitmap from " + url + e.toString());
} finally {
if (client != null) {
}
}
return null;
}
I think you are pretty close there. How about something similar to the below which downloads and saves an image:
try {
img_value = new URL("your_url");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
mIcon1 = BitmapFactory.decodeStream(img_value.openConnection()
.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String filename = "your_filename.jpg";
File file = new File(dir, filename);
if (file.exists()) {
try{
file.delete();
}catch(Exception e){
//sdcard plugged in
}
}
try {
FileOutputStream out = new FileOutputStream(file);
mIcon1.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();//will occur if the phone is plugged in
}

Categories

Resources