Serialize Object (jpg) to internal storage - android

I am trying to download a set of .jpg's from Amazon S3 and store them to the internal storage (so they can't be copied by a malicious user). I have gotten this far but now I am stuck. I have found multiple questions that deal with bitmaps or arrays but nothing about storing an image and then accessing it later. Anyone know where I go from here?
String itemName = iconNames.getString(iconNames.getColumnIndexOrThrow(DbAdapter.KEY_ICON));
itemName = itemName + ".jpg";
GetObjectRequest getObject = new GetObjectRequest(bucket, itemName);
S3Object icon = mS3Client.getObject(getObject);
InputStream input = icon.getObjectContent();
I have looked here in the dev guide and it gives the following code
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
But this is for storing a string, not an image...

You have to copy InputStream to OutputStream. Something like this:
InputStream input = icon.getObjectContent();
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = input.read(buf)) > 0) {
fos.write(buf, 0, len);
}
input.close();
fos.close();

You could do something like the following.
Bitmap bitmapPicture = someBitmap
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "tmp.png");
fOut = new FileOutputStream(file);
bitmapPicture.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());

Related

can't create folder on externalstorage

I'm trying to create a folder on external storage with no success.Although i've managed to create a folder in my app's directory, i can't do the same for external storage and i also get false when i call canWrite().I have declared the WRITE_EXTERNAL_PERMISSION on manifest.
Here is my code for my app's directory
File file1=new File(context.getFilesDir(), "//test1");
file1.mkdir();
System.out.println(file1.canWrite());
and for ExternalStorage respectively
File file2=new File(Environment.getExternalStorageDirectory(), "//test2");
file2.mkdir();
System.out.println(file2.canWrite());
In the first case the folder gets created and i get true on println.On the second one folder does not get created and i get false on println.
Add Below Permission i your manifest.xml
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
String PATH = Environment.getExternalStorageDirectory() + "/download/YourPath";
String fileName="Name for your File";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1)
{
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
This will create a directory,if you use comma,it means "//test2" will become a file name
String string = Environment.getExternalStorageDirectory().getPath() + "/test2";
File file = new File(string, "file_name");
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(your_data);
fileOutputStream.flush();
fileOutputStream.close();

How to make a file object of a file in the drawable or raw folder?

I want to bundle an image with my application. I am planing to keep the image in the drawable or the raw folder. I wanted to know how to make a File object of this image?
Something like this:
File file = new File("fileurl");
Thank you.
Can you please try this one ?
try {
File mFile=new File("my file name");
InputStream inputStream = getResources().openRawResource(R.drawable.ic_launcher);
OutputStream out=new FileOutputStream(mFile);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
out.write(buf,0,len);
out.close();
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
Hope this will help you.
If you put your image resource inside your Raw folder within your workspace, you can access it inside your class by using :
getResources.openRawResources(R.raw.resource_id)
EDIT :
the above code will return an inputStream, to convert it to file, try this one :
inputStream = getResources.openRawResources(R.raw.resource_id)`
// write the inputStream to a FileOutputStream
File file = new File("fileurl");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.close();
inputStream.close();

How to create folder in internal memory

This is my application memory path /data/data/com.myexample.folder/files and it works fine but when I create a new directory like this /data/data/com.myexample.folder/files/photos,
it is not created and I wonder what's wrong? How do I create a new folder inside application.
public void loadFeed();
String file paths="data/data/com.myapplication.myfolder/files";
File outputFiles= new file(filePaths);
File files1=outputFile1.listFiles();
For your own directory in file storage:
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/camtest");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);
For saving in sub directory inandroid public folders say DCIM:
use File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
Mainly, make sure that your app has the storage permission enabled:
Go to Device Settings>Device>Applications>Application Manager>"your app">Permissions>Enable Storage permission!
Call openFileOutput() with the name of the file and the operating mode.
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
just use this way:
public void createFile(Context c) throws IOException{
String FILENAME = timeStamp();
String string = "hello world!";
FileOutputStream fos = c.openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}

Eclipse: save image from drawable resource

I have to save an image in to a gallery from a drawable resource with a button and I have use this code:
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher3);
//generate file
String SDdirectory = Environment.getExternalStorageDirectory().getPath();
File externalStorageDir = Environment.getExternalStorageDirectory();
File f = new File(externalStorageDir, "Bitmapname.png");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG,0 , bos);
byte[] bitmapdata = bos.toByteArray();
try {
OutputStream os = new FileOutputStream (new File ("storage/sdcard0/iob"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
now the problem is that i save a file of 0kb... o.o
Thanks in advance .
I don't know, if there is a better solution, but this code works for me:
//at first I've imported the bitmap normally.
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.wall);
//generate file
File dir = new File ("/sdcard/foldername/");
File f = new File(dir, String.format("mybitmapname.png"));
//then write it to galery by adding this lines
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 , bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
bos.close();
Please make sure you have added this line in your manifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Try this:
OutputStream os = new FileOutputStream(new File("path/to/file"));
Beware, though. The way you copy data between the streams may easily lead to heap overflow if the resource is large. You should consider a smaller buffer reused as many times as needed to copy the whole data:
byte[] data = new byte[1024];
int len = 0;
while ((len = is.read(data)) > -1) {
os.write(data, 0, len);
}
Another consideration would be to move the whole copy operation to a separate thread (e.g. using AsyncTask) as not to block the UI thread. See the example here: http://developer.android.com/reference/android/os/AsyncTask.html
The file is File object that you want to write to.
BTW I will suggest to go for Apache Commons IO for doing file operations.
Refer -> this

Android: Faster way to read/write a ZipInputStream?

I am currently writing an application that reads a zip file in my assets folder which contains a bunch of images. I am using the ZipInputStream API to read the contents and then writing each file to my: Environment.getExternalStorageDirectory() directory. I have everything working but the first time the application is run writing the images to the storage directory is INCREDIBLY slow. It takes about about 5 minutes to write my images to disc. My code looks like this:
ZipEntry ze = null;
ZipInputStream zin = new ZipInputStream(getAssets().open("myFile.zip"));
String location = getExternalStorageDirectory().getAbsolutePath() + "/test/images/";
//Loop through the zip file
while ((ze = zin.getNextEntry()) != null) {
File f = new File(location + ze.getName());
//Doesn't exist? Create to avoid FileNotFoundException
if(f.exists()) {
f.createNewFile();
}
FileOutputStream fout = new FileOutputStream(f);
//Read contents and then write to file
for (c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
}
fout.close();
zin.close();
The process of reading the contents of the particular entry and then writing to it is VERY slow. I am assuming it is more to do with reading than writing. I've read that you can use a byte[] array buffer to speed up the process but this does not seem to work! I tried this but it only read part of the file...
FileOutputStream fout = new FileOutputStream(f);
byte[] buffer = new byte[(int)ze.getSize()];
//Read contents and then write to file
for (c = zin.read(buffer); c != -1; c = zin.read(buffer)) {
fout.write(c);
}
}
When I do that I only get about 600-800 bytes written. Is there a way to speed this up?? Have I implemented the buffer array incorrectly??
I found a much better solution which implements the BuffererdOutputStream API. My solution looks like this:
byte[] buffer = new byte[2048];
FileOutputStream fout = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fout, buffer.length);
int size;
while ((size = zin.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, size);
}
//Close up shop..
bos.flush();
bos.close();
fout.flush();
fout.close();
zin.closeEntry();
I managed to increase my load time from anywhere from an average of about 5 minutes to about 5 (depending on how many images are in the package). Hope this helps!
Try use http://commons.apache.org/io/
like:
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
try {
System.out.println( IOUtils.toString( in ) );
} finally {
IOUtils.closeQuietly(in);
}

Categories

Resources