Android - Save image to SD and then Load Image - android

I've designed quickly a piece of code which loads from an specified URL and then saves it to the SD card, however it is not saving to the SD.
URL myFileUrl = new URL( Image_HTML);
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath();
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bm = BitmapFactory.decodeStream(is);
FileOutputStream fos = new FileOutputStream(filepath+image_name);
bm.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
bm = BitmapFactory.decodeFile(filepath+image_name);
image_loader_view.setImageBitmap(bm);
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i("Hub", "FileNotFoundException: "+ e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.i("Hub", "IOException: "+ e.toString());
}
I have tried to make this code as lightweight as possible, and I have also activated the EXTERNAL.STORAGE.WRITE in the android manifest.

Couple things.
When you use a FileOutputStream you have to make sure the directory you are trying to write to is created before you try to write a file to it. If not you have to create it. This can be done via mkdirs() method of the File class.
Next I'm not sure the call to getAbsolutePath is required, due to the type of file system Android uses. I've never had to use it to save to SD before.
I'd try these and see if one of them will solve it for you.

Related

FTPClient in android convert image to bitmap

Help!! i have installed ApacheCommons.net FTPClient. As i need to download a PNG file via ftp. The stream downloads but iam having trouble converting it into a Bitmap so i can save to local storage.
mFTPClient.connect("path");
mFTPClient.login("anonymous","nobody");
mFTPClient.enterLocalPassiveMode();
mFTPClient.changeWorkingDirectory("/fax");
InputStream inStream = mFTPClient.retrieveFileStream("nweimage.PNG");
InputStreamReader isr = new InputStreamReader(inStream, "UTF8");
Been trying to use BitmapFactory to convert it, but just keep getting null return.
Any pointers
Cheers
This is how i got around it. Thanks greenapps for making me think down a different route
mFTPClient.connect("path");
mFTPClient.login("anonymous","nobody");
mFTPClient.enterLocalPassiveMode();
mFTPClient.changeWorkingDirectory("/fax");
mFTPClient.setControlEncoding("UTF-8");
mFTPClient.setFileType(FTPClient.BINARY_FILE_TYPE);
try{
FileOutputStream out = new FileOutputStream(file);
boolean status = mFTPClient.retrieveFile("image.PNG", out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

android downloaded images are not in correct format

I'm downloading some images from my webservice using the below code and it works perfectly fine but after they are downloaded and copied to sd card, they are unknown file types although they have .jpg at the end and my application still can load them into imageviews but I can't open any of those downloaded images via the device's gallery from file manager. Any idea?
Here's how I download and save the images:
public void downloadImage(String url, String fileName) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String[] fileNameSplit = fileName.split("\\.");
String fileNameMobile = fileNameSplit[0] + "-mob." + fileNameSplit[1];
URL urlConnection = new URL(url);
URLConnection connection = urlConnection.openConnection();
InputStream in = connection.getInputStream();
File outFile = new File(file.getPath() + "/" + fileNameMobile);
OutputStream out = new FileOutputStream(outFile);
copyFile(in, out);
out.close();
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
example file name in directory browsed by file manager:
_58df8aa6dbb44ff7b870b49a4b2d8efb-mob.jpg
Try this
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outStream);
Here's little example
File file = new File(file.getPath() + "/" + fileNameMobile);
FileOutputStream fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
It seems after I read the downloaded file name from the url, there's a \n is added to end of the code which resulted into making that file unknown and also I couldn't read the file later on using the same file name without \n but now by removing that \n from the end of the filename it works fine now.

What is the phone storage in Android devices?

I can pass sdcard location to my adb command using
file:///sdcard/Android/screen.bmp
What is the equivalent string, if my file is saved in phone memory instead of sdcard, will it be
file:///phone/Android/screen.bmp
That isn't necessarily how you access things saved internally on your phone.
Keep in mind how you save an image to internal storage:
Bitmap bitmap = ______; //get your bitmap however
try {
FileOutputStream fos = context.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
Log.e("Saving the bitmap",e.getMessage());
}
Now, to go read it, we just get the context, and call getFileStreamPath(filename) on it.
Bitmap retrievedImage;
String filename = "desiredFilename.png";
try {
File filePath = context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
retrievedImage = BitmapFactory.decodeStream(fi);
} catch (Exception e) {
Log.e("Retrieving the image", e.getMessage());
}
You can read more about this here.

How to create a file from google glass application?

I have an application that runs on glass. I want my application to create files at run time and be able to write/read data to/from those files. Can anyone show me a way to do this? Does Android's openFileOutput() work in glass?
(In case if anyone else has the same question)
Okay I figured out a way to do this. It looks like Java i/o libraries works fine with android and also for glass. The following works fine in glass.
String filename = "sensorData";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter (outputStream);
outputStreamWriter.write(content);
outputStreamWriter.close();
}
catch (Exception e) {
e.printStackTrace();
}
//Printing the file in logcat just to verify the contents
FileInputStream inputStream;
try
{
inputStream = openFileInput(filename);
InputStreamReader inputStreamReader = new InputStreamReader (inputStream);
char[] buffer = new char[content.length()];
inputStreamReader.read(buffer);
String input = buffer.toString();
Log.i(input);
}
catch (Exception e)
{
e.printStackTrace();
}

Android: write bytes to image file on SD Card

I'm trying to create an image file on sd-card, building it from the bytes that a server is sending towards me after calling a web-service (basically: download file).
I managed to get "something" on the client-side, and try to write those bytes to a file, using:
FileOutputStream fOut = null;
BufferedOutputStream bOs = null;
try {
fOut = new FileOutputStream(returnedFile);
bOs = new BufferedOutputStream(fOut);
bOs.write(bytesToWrite);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (bOs != null) {
bOs.close();
fOut.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
but the image file is broken (its size is > 0kb, but broken).
I ended up opening that file on my computer with a text editor, and I saw that some of the initial file data (before being sent), differs from the final one. So I'm guessing that there is some kind of encoding misstakening or something like that.
I would appreciate an idea of how to make this work ( download image file from a web server, and open in on my phone).
PS. I can also change or get info about the server configuration, as it was configured by a friend of mine.
PS2. I should be able not to download only images, but any kind of file.
I think It's better you encode the image to Base64 in your server, for example in PHP you can do it like this :
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
And then in android you decode the Base64 string into your image file:
FileOutputStream fos = null;
try {
if (base64ImageData != null) {
fos = context.openFileOutput("imageName.png", Context.MODE_PRIVATE);
byte[] decodedString = android.util.Base64.decode(base64ImageData, android.util.Base64.DEFAULT);
fos.write(decodedString);
fos.flush();
fos.close();
}
} catch (Exception e) {
} finally {
if (fos != null) {
fos = null;
}
}
First of all make sure you have this permissions on your android manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
File stream is designed to work on local file storage rather than network connection. Use URLConnection class instead.
URL uri = new URL("Your Image URL");
URLConnection connection = uri.openConnection();
InputStream stream = connection.getInputStream();
//DO other stuff....

Categories

Resources