Eclipse: save image from drawable resource - android

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

Related

Compare size of file and size of byte array of that file

When we convert the file (say - image)
To byteArray how can be approximately compared between them (image file and byteArray) ?
Is there also a way to first convert image file to byteArray and this byteArray has to be written in a text-file..
Again after this read these lines of byteArray from text-file and make byteArray and hence converted to image file...... I'm beginner and just for knowledge purpose i want to know....
You can convert your image to byte array like this.
BufferedImage bImage = ImageIO.read(new File("sample.jpg"));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", bos );
byte [] data = bos.toByteArray();
Yes you can directly compare 2 byteArray.
Just do something like
if (bytearray1.length == bytearray2.length)
//its same
Try this to write the ByteArray in text file
public void writeToFile(byte[] array)
{
try
{
String path = "/data/data/YOURFILE.txt"; //provide your path here
File file = new File(path);
if (!file.exists()) { //just to check if file is actually present
file.createNewFile();
}
FileOutputStream stream = new FileOutputStream(path);
stream.write(array);
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}

mp3 not saving to sd correctly; how to save mp3 to sd card?

I've been looking at this site for the past 3 or so hours. How to copy files from 'assets' folder to sdcard?
This is the best I could come up with because I'm only trying to copy one file at a time.
InputStream in = null;
OutputStream out = null;
public void copyAssets() {
try {
in = getAssets().open("aabbccdd.mp3");
File outFile = new File(root.getAbsolutePath() + "/testf0lder");
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: ", e);
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
I've figured out how to create a file and save a text file. http://eagle.phys.utk.edu/guidry/android/writeSD.html
I would rather save an mp3 file to the sdcard rather than a text file.
When I use this code I provided, I get a text document that same size as the aabbccdd.mp3 file. It does not create a folder and save an .mp3 file. It saves a text document in the root folder. When you open it, I see a whole bunch of chinese letters, but at the top in English I can see the words WireTap. WireTap Pro was the program I used to record the sound so I know the .mp3 is passing through. It's just not creating a folder and then saving a file like the above .edu example.
What should I do?
I think you should do something like that -[Note: this i used for some other formats not mp3 but its works on my app for multiple format so i hope it will work for u too.]
InputStream in = this.getAssets().open("tmp.mp3"); //give path as per ur app
byte[] data = getByteData(in);
Make sure u have the folder already exists on path, if folder is not there it will not save content correctly.
byteArrayToFile(data , "testfolder/tmp.mp3"); //as per ur sdcard path, modify it.
Now the methods ::
1) getByteData from inputstream -
private byte[] getByteData(InputStream is)
{
byte[] buffer= new byte[1024]; /* or some other number */
int numRead;
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try{
while((numRead = is.read(buffer)) > 0) {
bytes.write(buffer, 0, numRead);
}
return bytes.toByteArray();
}
catch(Exception e)
{ e.printStackTrace(); }
return new byte[0];
}
2) byteArrayToFile
public void byteArrayToFile(byte[] byteArray, String outFilePath){
FileOutputStream fos;
try {
fos = new FileOutputStream(outFilePath);
fos.write(byteArray);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}

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();

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);
}

Android: How to download a .png file using Async and set it to ImageView?

I've got the URL of a .png image, that needs to be downloaded and set as a source of an ImageView. I'm a beginner so far, so there are a few things I don't understand:
1) Where do I store the file?
2) How do I set it to the ImageView in java code?
3) How to correctly override the AsyncTask methods?
Thanks in advance, will highly appreciate any kind of help.
I'm not sure you can explicity build a png from a download. However, here is what I use to download images and display them into Imageviews :
First, you download the image :
protected static byte[] imageByter(Context ctx, String strurl) {
try {
URL url = new URL(urlContactIcon + strurl);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And then, create a BitMap and associate it to the Imageview :
bytes = imagebyter(this, mUrl);
bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
yourImageview.setImageBitmap(bm);
And that's it.
EDIT
Actually, you can save the file by doing this :
File file = new File(fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(imagebyter(this, mUrl));
fos.close();
You can explicity build a png from a download.
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
100 is your compression (PNG's are generally lossless so 100%)
out is your FileOutputStream to the file you want to save the png to.

Categories

Resources