download data in byte[] in android - android

I want download data in a byte[] and when save it in a jpg file it's show image.
I can do it but I have problem.
if I use this code to download data it doesn't have any problem but in this case the download speed is low :
String urlAddress = urlAddresses[0];
try {
URL url = new URL(urlAddress);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
int fileLength = httpURLConnection.getContentLength();
InputStream inputStream = httpURLConnection.getInputStream();
byte[] buffer = new byte[1];
int curLength = 0;
int newLength = 0;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while((newLength = inputStream.read(buffer))>0)
{
curLength += newLength;
publishProgress(fileLength != 0 ? (curLength*100)/fileLength : -1);
byteArrayOutputStream.write(buffer);
}
if(fileLength > 0 && curLength != fileLength)
{
Byte[] result = new Byte[1];
result[0] = ERROR_FILE_LENGTH;
return result;
}
complate = true;
byte[] resultByteArray = byteArrayOutputStream.toByteArray();
Byte[] result = new Byte[resultByteArray.length];
for(int i=0; i<result.length; i++)
result[i] = resultByteArray[i];
return result;
}
catch (IOException e)
{
e.printStackTrace();
Byte[] result = new Byte[1];
result[0] = ERROR_DOWNLOAD_FAILED;
return result;
}
but if i change this line : byte[] buffer = new byte[1] to byte[] buffer = new byte[1024] download speed go up but when I save it in a somename.jpg file it doesn't show image
String urlAddress = urlAddresses[0];
try {
URL url = new URL(urlAddress);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
int fileLength = httpURLConnection.getContentLength();
InputStream inputStream = httpURLConnection.getInputStream();
byte[] buffer = new byte[1024];
int curLength = 0;
int newLength = 0;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while((newLength = inputStream.read(buffer))>0)
{
curLength += newLength;
publishProgress(fileLength != 0 ? (curLength*100)/fileLength : -1);
byteArrayOutputStream.write(buffer);
}
if(fileLength > 0 && curLength != fileLength)
{
Byte[] result = new Byte[1];
result[0] = ERROR_FILE_LENGTH;
return result;
}
complate = true;
byte[] resultByteArray = byteArrayOutputStream.toByteArray();
Byte[] result = new Byte[resultByteArray.length];
for(int i=0; i<result.length; i++)
result[i] = resultByteArray[i];
return result;
}
catch (IOException e)
{
e.printStackTrace();
Byte[] result = new Byte[1];
result[0] = ERROR_DOWNLOAD_FAILED;
return result;
}
note : in this case I want save data to just byte[] and save file normaly wit FileOutputStream and ... after I get full byte[] and download finished;
tahnks

change:
byteArrayOutputStream.write(buffer);
to:
byteArrayOutputStream.write(buffer, 0, newLength);

Related

Not able to convert image from url into byte array

I am new to android and I need to save image from url into db and fetch it from db. I an converting image from link into byte array but getting the following error:
Cannot Resolve ByteArrayBuffer
This is the code:
private byte[] getLogoImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
Update your method getLogoImage() as below.
Use AsyncTask and call this method from doInBackground().
Here is the working code. Try this:
private byte[] getLogoImage(String url) {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
while ((read = is.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, read);
}
baos.flush();
return baos.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
Try like this
Bitmap bm = null;
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
byte[] imageArray = getBytes(bm);
and after this use below method
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
return stream.toByteArray();
}
Use This
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
Bitmap bitmap = BitmapFactory.decodeFile(url,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();

How to convert file to base64Binary in android?

Below code is for convert file to bytearray.
public static byte[] convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
#SuppressWarnings("resource")
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 8];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return byteArray;
}
But I need a code for convert file to binary format.
try this:
Get your byte array file:
File file= new File("path file");
byte[] fileByte=convertFileToByteArray(file);
Then convert to base64 in byte array:
byte[] file_in_base64 = Base64.encode(fileByte, Base64.DEFAULT);
Convert byte array to binary:
String toBinary( byte[] bytes )
{
StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
for( int i = 0; i < Byte.SIZE * bytes.length; i++ )
sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
return sb.toString();
}

Getting outofmemoryerror while downloading images to a coverflow for an android app

Through web service i am writing each image in to a JPG file(in sdcard- "mnt/sdcard/img.jpg") and showing the images in to a coverflow view.i am getting the first image but when it comes to the second and other images i am getting outofmemoryerrorr.
below i have given the code to get the image from url
public Bitmap getImageDirectHit(String directHitUrl){
Bitmap bmImg;
String fileUrl=directHitUrl;
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bmImg = null;
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
//int length = conn.getContentLength();
InputStream is = conn.getInputStream();
//conn.disconnect();
// BufferedInputStream bis = new BufferedInputStream(is);
// ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(50);
// int current = 0;
// while ((current = bis.read()) != -1) {
// byteArrayBuffer.append((byte) current);
// }
//
File nf = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
FileOutputStream fos = new FileOutputStream(nf);
//byte[] buf = new byte[2048];
//int n;
// fos.write(bitmapdata, 0, bitmapdata.length);
byte[] bufu=new byte[20];
int len = 0;
while((len = is.read(bufu))>0) {
fos.write(bufu);
}
fos.close();
fos = null;
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// int next = is.read();
// while (next > -1) {
// bos.write(next);
// next = is.read();
// }
// bos.flush();
// byte[] result = bos.toByteArray();
// bos.close();
// bos = null;
Bitmap tempBitmap =
BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
//Bitmap tempBitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
//result = null;
bmImg = Bitmap.createScaledBitmap(tempBitmap, 150, 180, true);
tempBitmap.recycle();
tempBitmap = null;
// bmImg = BitmapFactory.decodeStream(is);
// Log.i("Byte Array Size", ":"+byteArrayBuffer.length());
// bis.close();
is.close();
// bis = null;
is = null;
return bmImg;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}

Convert a BufferedInputStream to a File

I am loading a image from the web to the local android phone. The code that I have for writing to a file is as follows
BufferedInputStream bisMBImage=null;
InputStream isImage = null;
URL urlImage = null;
URLConnection urlImageCon = null;
try
{
urlImage = new URL(imageURL); //you can write here any link
urlImageCon = urlImage.openConnection();
isImage = urlImageCon.getInputStream();
bisMBImage = new BufferedInputStream(isImage);
int dotPos = imageURL.lastIndexOf(".");
if (dotPos > 0 )
{
imageExt = imageURL.substring(dotPos,imageURL.length());
}
imageFileName = PATH + "t1" + imageExt;
File file = new File(imageFileName);
if (file.exists())
{
file.delete();
Log.d("FD",imageFileName + " deleted");
}
ByteArrayBuffer baf = new ByteArrayBuffer(255);
Log.d("IMAGEWRITE", "Start to write image to Disk");
int current = 0;
try
{
while ((current = bisMBImage.read()) != -1)
{
baf.append((byte) current);
}
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("IMAGEWRITE", "Image write to Disk done");
}
catch (IOException e)
{
e.printStackTrace();
}
isImage.close();
}
catch (IOException e)
{
Log.d("DownloadImage", "Error: " + e);
}
finally
{
isImage = null;
urlImageCon = null;
urlImage = null;
}
For some reason the whole writing to a file takes 1 minute. Is there a way I can optimize this ?
Your buffer is very small: 255 bytes. You could make it 1024 times bigger (255 kilobytes). This is an acceptable size and this would certainly speed up the thing.
Also, this is very slow as it reads the bytes one by one:
while ((current = bisMBImage.read()) != -1) {
baf.append((byte) current);
}
You should try using the array version of read() instead: read(byte[] buffer, int offset, int byteCount) with an array as large as what I have described above.
You should use the Android HttpClient for file fetching over the java URL Connection. Also your Buffer is very small.
Try this snipped:
FileOutputStream f = new FileOutputStream(new File(root,"yourfile.dat"));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
InputStream is = response.getEntity().getContent();
byte[] buffer = new byte[1024];
int len1 = 0;
while ( (len1 = is.read(buffer)) > 0 ) {
f.write(buffer,0, len1);
}
f.close();

GZip in android [duplicate]

This question already has answers here:
How can I Zip and Unzip a string using GZIPOutputStream that is compatible with .Net?
(10 answers)
Closed 8 years ago.
How to compress and decompress a file in android using GZip. please provide with some reference , so that it would a great help for me.
Thanks in advance
Please use the following methods to compress the string using gzip.
public static byte[] compress(String string) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(string.getBytes());
gos.close();
byte[] compressed = os.toByteArray();
os.close();
return compressed;
}
public static String decompress(byte[] compressed) throws IOException {
final int BUFFER_SIZE = 32;
ByteArrayInputStream is = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
StringBuilder string = new StringBuilder();
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gis.read(data)) != -1) {
string.append(new String(data, 0, bytesRead));
}
gis.close();
is.close();
return string.toString();
}
Check out GZIPInputStream and GZIPOutputStream.
I ran into same problem some time ago. Here are the functions i used
Compress Function
if (responseCode == HttpConnection.HTTP_OK){
boolean stop = false, pause = false;
totalSize = conn.getLength() + downloaded;
chunkSize = (int)(conn.getLength() / 100);
System.out.println("*********-----" + conn.getLength() + "");
System.out.println("-----------------ok");
in = conn.openInputStream();
int length = 0, s = 0;
byte[] readBlock = new byte[(int)conn.getLength()];
while ((s = in.read(readBlock) != -1)
length = length + s;
{
if (!pause)
{
readBlock = Decompress.decompress(readBlock);
out.write(readBlock, 0, length);
downloaded += length;
int a = getPerComplete(totalSize, downloaded);
System.out.println("% OF Downloaded--------" + a);
int a1 = getPerComplete(totalSize, downloaded);
Decompress function:-
public byte[] decompress(byte[] compressed) throws IOException
{
GZIPInputStream gzipInputStream;
if (compressed.length > 4)
{
gzipInputStream = new GZIPInputStream(
new ByteArrayInputStream(compressed, 4,
compressed.length - 4));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (int value = 0; value != -1;)
{
value = gzipInputStream.read();
if (value != -1)
{
baos.write(value);
}
}
gzipInputStream.close();
baos.close();
return baos.toByteArray();
}
else
{
return null;
}
}
}

Categories

Resources