Writing/Reading gif internal storage - java

I'm trying to load a gif from a url to be displayed in an Imageview, store it in the internal storage and then later read it again. But it refuses to either store the image or reading it, not sure which one because I get no exceptions. Loading the image to the imageview works. The first method below (loadImage())
public Bitmap loadImage(String url){
Bitmap bm = null;
URL request;
try {
if(url!=null){
request = new URL(url);
InputStream is = request.openStream();
bm = BitmapFactory.decodeStream(is);
is.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
public String writeGifToInternalStorage (Bitmap outputImage) {
try {
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
ByteBuffer byteBuffer = ByteBuffer.allocate(outputImage.getByteCount());
outputImage.copyPixelsToBuffer(byteBuffer);
byteBuffer.flip();
byte[] data = new byte[byteBuffer.limit()];
byteBuffer.get(data);
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(data);
fos.close();
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public Bitmap readFileFromInternalStorage(String filename) {
if (filename == null) return null;
FileInputStream fis;
try {
fis = ctx.openFileInput(filename);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
Any ideas of whats wrong?

Your method readFileFromInternalStorage read an encoded image from the file system. This image file should be what you receive from the server.
For that, you need to save the image when you receive it from the server, for example like so:
InputStream is = new BufferedInputStream(request.openStream());
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int red = 0;
while ((red = is.read(buffer)) != -1) {
fos.write(buffer,0, red);
}
fos.close();
is.close();
Then, your image is saved to the disk, and you can open it using your readFileFromInternalStorage method.
Also, if you use HttpClient instead of URL, I wrote a one-liner for downloading a file: Android download binary file problems

Related

After downloading whole (84M) file from dropbox it turning into 0 bytes

I am downloading a zip file from dropbox. When it keeps downloading I measure the file size and get it is increasing its size with the Below code. It downloads whole 84M and after finishing download it turns into 0 bytes. What wrong am I actually doing?
public static void downloadDropBox(File file) {
String url = "https://www.dropbox.com/sh/jx4b2wvqg8d4ze1/AAA0J3LztkRc6FJ5tKy4dUKha?dl=1";
int bytesRead;
byte[] bytesArray = new byte[1024];
InputStream is = null;
FileOutputStream outputStream = null;
long progres = 0;
try {
URL fileUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection)fileUrl.openConnection();
connection.connect();
is = connection.getInputStream();
outputStream = new FileOutputStream(file);
while ((bytesRead = is.read(bytesArray, 0, 1024)) != -1) {
outputStream.write(bytesArray, 0, bytesRead);
}
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
During download file:
After Finishing download file:

Android: Saving .png from URL into app internal storage

I'm relatively new to android, and I'm trying to modify an android app such that it downloads a profile picture (preferably in PNG) from a URL, and saves it in the com.companyName.AppName.whatever/files. It should be noted that the app was initially created in Unity, and just built and exported.
Here's my initial code:
URL url = null;
try {
url = new URL(playerDO.getProfileURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStream input = null;
try {
input = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[256];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: Here's my other code, as suggested by #Ashutosh Sagar
InputStream input = null;
Bitmap image = null;
try {
input = url.openStream();
image = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
File myDir = getFilesDir();
try {
Log.wtf("DIRECTORY", myDir.toString());
File imageFile = new File(myDir, fileName);
if (!imageFile.exists()){
imageFile.createNewFile();
Log.wtf("ANDROID NATIVE MSG: WARN!", "File does not exist. Writing to: " + imageFile.toString());
}
outputStream = new FileOutputStream(imageFile, false);
image.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
Log.wtf("AWWW CRAP", e.toString());
}
}
(It doesn't write either).
Unfortunately, I've had several problems with this. My primary issue is that when it (on the cases that it does) runs, it actually doesn't save anything. I'll go and check com.companyName.AppName.whatever/files directory only to find no such .png file. I will also need it to overwrite any existing files of the same name, which is hard to check when it doesn't work.
My secondary issue is that it fails to take into account delays in internet connection. Although I've put in enough try-catch clauses to stop it from crashing (as it used to), the end result is that it also doesn't save.
How can I improve upon this? Anything I'm missing?
EDIT:
Printing out the directory reveals it should be in:
/data/user/0/com.appName/files/5965e9e4a0f0463853016e2b.png
However, using ES File explorer, the only thing remotely close to that is
emulated/0/Android/data/com.appName/files/
Are they the same directory?
try this first get bitmap image from url
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
and to save bitmap image please check the ans of GoCrazy
Try this
void getImage(String string_url)
{
//Generate Bitmap from URL
URL url_value = new URL(string_url);
Bitmap image =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
//Export File to local Directory
OutputStream stream = new FileOutputStream("path/file_name.png");
/* Write bitmap to file using JPEG or PNG and 80% quality hint for JPEG. */
bitmap.compress(CompressFormat.PNG, 80, stream);
stream.close();
}

saving downloaded file to internal storage java/android fails

I have an app who has to download some generated images (PNG).
I tried the standard approach ImageDownloader extends AsyncTask, doInBackground() retrieves the image and the onPostExecute() will try to save it to internal image.
(Part of the) code is below:
public class HandleImages extends AppCompatActivity {
String filename = "";
public boolean saveImageToInternalStorage(Bitmap image) {
try {
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Bitmap retrieveImage(String url){
ImageDownloader task = new ImageDownloader();
Bitmap image = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
try {
image = task.execute(url).get();
} catch (InterruptedException e) {
MainActivity.debb("InterruptedException - " + e.getMessage() + " in " + new Object(){}.getClass().getEnclosingMethod().getName());
e.printStackTrace();
} catch (ExecutionException e) {
MainActivity.debb("ExecutionException - " + e.getMessage() + " in " + new Object(){}.getClass().getEnclosingMethod().getName());
e.printStackTrace();
}
return image;
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
try {
String[] filenames = urls[0].split("/");
filename = filenames[filenames.length-1] + ".jpg";
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputStream = connection.getInputStream();
return BitmapFactory.decodeStream(inputStream);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (bitmap != null)
saveImageToInternalStorage(bitmap);
}
}
}
and the error that I get is: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileOutputStream android.content.Context.openFileOutput(java.lang.String, int)' on a null object reference.
It seems that the FileOutputStream fos = openFileOutput(..) fails, but have no idea why.
Also tried to prepend a path (sdCard.getPath() + "/" +) to the filename. As expected it did not make any difference.
Images are ok, I can see them in the browser. Also tried with uploaded images - instead of the generated ones, same result.
This is pretty odd, does anyone have any idea?
Thanks!
private String saveToInternalStorage(Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File mypath=new File(directory,"profile.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return directory.getAbsolutePath();
}
Hope this function helps you. If this doesn't help feel free to ask

java.io.utfdataformatexception: String is too long

I am getting the exception as in the Title while sending an image to a java server
Here's the code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
img.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
String imageDataString = new String(Base64.encodeBase64(byteArray));
System.out.println(imageDataString);
dataOutputStream.writeUTF(imageDataString);
dataOutputStream.flush();
Where img is a bitmap file.
Any help will be highly appreciated !
#Sarram follow the code in the blow link, I was sending images in soap request along with other data in the form of base64String the i was converting it into file
blow is the reference of code
Writing decoded base64 byte array as image file
I am using this cool decoder import sun.misc.BASE64Decoder;
Server side can do it like that
String filePath = "/destination/temp/file_name.jpg";
File imageFile = new File(filePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);//create file
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
BASE64Decoder decoder = new BASE64Decoder();//create decodeer object
byte[] decodedBytes = null;
try {
decodedBytes = decoder.decodeBuffer(imageFileBase64);//decode base64 string that you are sending from clinet side
} catch (IOException e1) {
e1.printStackTrace();
}
try {
fos.write(decodedBytes);//write the decoded string on file and you have ur image at server side
} catch (IOException e) {
e.printStackTrace();
}
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}

Use SD card for inputStream (images) android instead of internal memory

I'm trying to grab (with the method below) an image from the internet and do some canvas work with. but sometimes i'm having outOfMemory exception. So i'm wondering if is there a way to load the inputStream directly in the memory card instead of the internal memory.
private Bitmap LoadImageFromWebOperations(String url)
{
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
bitmap = ((BitmapDrawable)d).getBitmap().copy(Config.ARGB_8888, true);
return bitmap;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
the logcat says that the exception is due to that line :
Drawable d = Drawable.createFromStream(is, "src name");
Thx in advance!
I took this code from Fedor Vlasov's lazylist demo:
Lazy load of images in ListView.
First you need to create a function to copy your input stream to file output stream:
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
Then get a cache folder:
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"MyCacheDir");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
Then load your bitmap:
private Drawable getBitmap(String url)
{
String filename=URLEncoder.encode(url);
File f= new File(cacheDir, filename);
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f));
return new BitmapDrawable(bitmap);
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}

Categories

Resources