Save .gif to sd card - java

I am still new in Android programming,
and I wanna do something,
download .gif from url
save that downloaded .gif to my sd card
call it using glide
When I download .gif, and write it to sdcard, it is not readable.
and the size bigger than original file.
here is the code I use :
URL url = new URL(imgUrl + params[0]);
File file = new File(path + params[0]);
long startTime = System.currentTimeMillis();
URLConnection ucon = url.openConnection();
Log.d(TAG, "on do in background, url open connection");
InputStream is = ucon.getInputStream();
Log.d(TAG, "on do in background, url get input stream");
BufferedInputStream bis = new BufferedInputStream(is);
Log.d(TAG, "on do in background, create buffered input stream");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Log.d(TAG, "on do in background, create buffered array output stream");
byte[] img = new byte[1024];
int current = 0;
Log.d(TAG, "on do in background, write byte to baos");
while ((current = bis.read()) != -1) {
baos.write(img, 0, current);
}
Log.d(TAG, "on do in background, done write");
Log.d(TAG, "on do in background, create fos");
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
Log.d(TAG, "on do in background, write to fos");
fos.flush();
fos.close();
is.close();
Log.d(TAG, "on do in background, done write to fos");
thx before.

baos.write(img, 0, current); means to write current zeros (current byte from img).
Try changing the line to baos.write(current);.

Related

Video is not downloading from a URL

i want to download video from URL my function is as below
String fileURL = "http://192.168.1.2/UserFiles/Videos/OutputVideo/Birthday%20Bash5tV3fgjf4Sfi11sC.mp4";
String fileName = "Abc.mp4";
public void downloadFile(String fileURL, String fileName){
Toast.makeText(getApplicationContext(), "Download File", Toast.LENGTH_LONG).show();
try
{
URL u = new URL(fileURL);
URLConnection ucon = u.openConnection();
//Define InputStreams to read from the URLConnection.
// uses 3KB download buffer
File file =new File(Environment.getExternalStorageDirectory() + File.separator + "/Planetskool/Media/Videos/"+fileName);
InputStream is = ucon.getInputStream();
BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
FileOutputStream outStream = new FileOutputStream(file);
byte[] buff = new byte[5 * 1024];
//Read bytes (and store them) until there is nothing more to read(-1)
int len;
while ((len = inStream.read(buff)) != -1)
{
outStream.write(buff,0,len);
}
//clean up
outStream.flush();
outStream.close();
inStream.close();
}
catch (Exception se)
{
se.printStackTrace();
}
}
its downloading video in 0kb whats wrong with this
use async method to download file from URL.
Three things might be happened
Missing Internet permission
Missing Write external storage permission
"/Planetskool/Media/Videos/" Directory not exist, Create dir first.
http://192.168.1.2 it is not internet URL check your URL

java download image directly to specified area

I already tried to download the image like this:
File file4 = new File("C:\\Users\\" + user + "\\AppData\\Roaming"
+ "\\.MINECRAFT2D\\Recources\\"
+ "tileset_texture_new_now.png");
try {
Image image = null;
URL url = new URL("http://www.mediafire.com/view/"
+ "htgmcgtg7yo5swy/tileset_texture_new_now.png");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(file4);
fos.write(response);
fos.close();
} catch (Exception e) {}
but it leaves an un-viewable image in the location. The image will say: "Photo Gallery can't open this photo or video. The file may be unsupported, damaged or corrupted." Is there a way to fix it?
try like this:
byte[] response = out.toByteArray();
Close the stream once you made the byte array
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
byte[] response = out.toByteArray();
out.close();
in.close();
Your url is pointing to 'http://www.mediafire.com/view/htgmcgtg7yo5swy/tileset_texture_new_now.png'. It does not resolve to an image/png. I believe that this is the reason of the corrupted image.
Take a look at FileUtils.copyURLToFile(URL, File), from Apache IO Commons. It might help you downloading files.

Android how to use Environment.getExternalStorageDirectory() corretly

Android how to use Environment.getExternalStorageDirectory()
How can i use Environment.getExternalStorageDirectory() to read/write a image from the SD card ? or is there a better way to do it?
I did use the source to download e save the image:
try {
URL url = new URL(urlBaseImagem + icone);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conection.getContentLength();
//
// download the file
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream
//File sdCard = Environment.getExternalStoragePublicDirectory(DOWNLOAD_SERVICE);
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/cardapioweb/rest/");
if(directory.exists() == false){
directory.mkdirs();
}
File outputFile = new File(directory, icone);
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
//publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
Log.w("CardapioWeb:" , "Imagem " + outputFile.toString() + " salva no sdcard");
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
I did use the source to load e show the image:
File arq = new File(this.sdCard.getAbsolutePath() + "/cardapioweb/rest/" + filialDataCollection.get(position).get(KEY_ICONE));
//verifica se a imagem foi baixada com sucesso
if(arq.exists() == true){
//deve exibir a imagem do sdcard
File outputFile1 = new File(this.sdCard.getAbsolutePath() + "/cardapioweb/rest/", filialDataCollection.get(position).get(KEY_ICONE));
Drawable imagem = Drawable.createFromPath(outputFile1.toString());
holder.tvWeatherImage.setImageDrawable(imagem);
}
The above codes works perfectly fine on the emulator (Android Virtual Device) with Eclipse !!!!
But when I generate the apk and install on my Galaxy S4, the app can not read images (no error is generated). Just does not display the images. What could be wrong?
Put a log in your code to see what
outputFile1.toString();
actually points to, is it what you expect?
Personally, I would have used outputFile1.getAbsolutePath(); NOT the line below:
Drawable imagem = Drawable.createFromPath(outputFile1.toString());

Displaying an image from an InputStream

I am able to send strings from my Android mobile phone to my computer, and vice versa. However, I want to send an image from my computer and display it to the mobile phone. In my case, the computer is the server and the mobile phone is the client.
This is part of my code on the server side:
socket = serverSocket.accept();
dataOutputStream = new DataOutputStream(socket.getOutputStream());
captureScreen("C:\\Users\\HP\\Desktop\\capture.png");
File f = new File("C:\\Users\\HP\\Desktop\\capture.png");
byte [] buffer = new byte[(int)f.length()];
dataOutputStream.write(buffer,0,buffer.length);
dataOutputStream.flush();
Note that captureScreen() is a method that successfully takes a screenshot of the server and save it as a .PNG image in the above path.
Now, on the client side which is the Android mobile phone, if I have an ImageView control, how to read the image sent from the computer as an InputStream and display it on the ImageView?
Furthermore, did I write successfully the image to the dataOutputStream? I would be glad if any one helps me !
You can call the setImageBitmap(Bitmap bm) of your ImageView.
http://developer.android.com/reference/android/widget/ImageView.html
How you get the image data to your client: it depends on the solution you have chosen, but technically you can use the same libraries that you would use for pure Java.
You can use android.graphics.BitmapFactory to create the Bitmap from your stream.
http://developer.android.com/reference/android/graphics/BitmapFactory.html
Bitmap bitmap1 = BitmapFactory.decodeStream(inputStream);
Bitmap bitmap2 = BitmapFactory.decodeFile(filename);
what is this ?
byte [] buffer = new byte[(int)f.length()];
dataOutputStream.write(buffer,0,buffer.length);
You just declared size of a buffer byte array , but it`s empty!
You should to convert your file to byte and than transfer it to OutputStream , smth like this:
byte[] buffer = System.IO.File.ReadAllBytes("C:\\Users\\HP\\Desktop\\capture.png");
(code for c#)
And than you will send it like you did:
dataOutputStream.write(buffer,0,buffer.length);
dataOutputStream.flush();
try this for file receiving :
public void fileReceived(InputStream is)
throws FileNotFoundException, IOException {
Log.i("IMSERVICE", "FILERECCC-1");
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream("/sdcard/chats/gas1.jpg/");
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead;
while ((bytesRead = is.read(aByte)) != -1) {
bos.write(aByte, 0, bytesRead);
}
bos.flush();
bos.close();
Log.i("IMSERVICE", "FILERECCC-2");
} catch (IOException ex) {
// Do exception handling
}
}
}
}
So you`ll got new file in your sd-card on Android.

file not saved correctly

Im trying to get image using webservice and saved to sd card. The file saved but i couldnt open the file. Once i open the file it saying "could not load image". Below is my code.
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
test = response.toString();
Blob picture = org.hibernate.Hibernate.createBlob(test.replaceAll("-", "").getBytes());
String FILENAME = "voucher1.jpg";
File root = Environment.getExternalStorageDirectory();
FileOutputStream f = new FileOutputStream(new File(root, FILENAME));
InputStream x=picture.getBinaryStream();
int size=x.available();
byte b[]= new byte[size];
x.read(b);
f.write(b);
f.close();
Please help. Thanks
I changed the format..instead use web service i just use the image url to retrieve the image and it works...
i try this and its work fine. Thanks.
URL url = new URL(fileURL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/caldophilus.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
i assume you need to call f.flush() in order to write out all data in stream to file.
f.flush();
f.close();

Categories