Dear all I am using below code to download the picture in android,
Where _in is as Input Stream and DataInputStream _din .
I use one URL to download the picture.but sometimes it returning me picture and sometimes it not showing null in bitmap.I have one question here, one is this good way to download picture or suggestion what can be wrong in this picture that same code sometimes returning picture and sometimes it not working ?
if (_in == null) {
_in = urlConnection.getInputStream();
}
if (_din == null) {
_din = new DataInputStream(_in);
}
byte[] data = new byte[0];
byte[] buffer = new byte[512];
int bytesRead;
while ((bytesRead = _din.read(buffer)) > 0) {
byte[] newData = new byte[data.length + bytesRead];
System.arraycopy(data, 0, newData, 0, data.length);
System.arraycopy(buffer, 0, newData, data.length, bytesRead);
data = newData;
}
InputStream is = new ByteArrayInputStream(data);
Bitmap bmp = BitmapFactory.decodeStream(is);
Try this and tell me whether you problem still occurs.
Bitmap ret;
HttpURLConnection conn = null;
try
{
URL u = new URL(mUrl);
conn = (HttpURLConnection) u.openConnection();
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setReadTimeout(CONNECTION_TIMEOUT);
conn.setDoInput(true);
conn.setRequestMethod("GET");
int httpCode = conn.getResponseCode();
if (httpCode == HttpURLConnection.HTTP_OK || httpCode == HttpURLConnection.HTTP_CREATED)
{
InputStream is = new BufferedInputStream(conn.getInputStream());
ret = BitmapFactory.decodeStream(is);
}
else
{
ret = null;
}
}
catch (Exception ex)
{
ret = null;
}
finally
{
if (conn != null)
{
conn.disconnect();
}
}
Why do you use a temp buffer for your image InputStream? Just use the UrlConnection InputStream directly with the BitmapFactory:
_in = urlConnection.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(_in);
This should always work if your images are ok.
Related
i'm trying to make a andoid application using youtube.
i'd like to upload a video using URL.
with my codes, i received 200 http status code and success message, but actually it doesn't.
how can i resolve it?
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Authorization", String.format("Bearer %s", access_token));
conn.setRequestProperty("Content-Type", "video/*");
conn.setRequestProperty("Content-Length", ContentLength);
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
int numberBytes = fis.available();
byte bytearray[] = new byte[numberBytes];
Log.e(" FileLength", String.valueOf(bytearray.length));
for(int i = 0; i < bytearray.length; i++)
dos.write(bytearray[i]);
dos.flush();
fis.close();
dos.close();
int responseCode = conn.getResponseCode();
if(responseCode == 200) {
Log.e("ResponseCode", String.valueOf(responseCode));
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] byteBuffer = new byte[1024];
byte[] byteData = null;
int nLength = 0;
while((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) {
baos.write(byteBuffer, 0, nLength);
}
byteData = baos.toByteArray();
String response = new String(byteData);
Log.e("RESPONSE", response);
}
} catch(Exception e) {
e.printStackTrace();
}
Use this library project
The code is a reference implementation for an Android OS application that captures video, uploads it to YouTube,
Detailed Answer: uploading using above library project
url="http://www.nasa.gov/sites/default/files/styles/946xvariable_height/public/ladee_spin_2_in_motion_0_0.jpg?itok=yNhf69rE";
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
I was tryning to retreive image from the url but no matter what it always returns null. In debugging mode I have observed that it happens when it tries input.close(); .
How can I possibly get the Image.
This is a proper way to load Bitmap:
InputStream is;
Bitmap bitmap;
is = context.getResources().openRawResource(DRAW_SOURCE);
bitmap = BitmapFactory.decodeStream(is);
try {
is.close();
is = null;
} catch (IOException e) {
}
However, as I see you close stream before finish to decoding it.
If so, use other way:
Bitmap bitmap;
InputStream input = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(input, 8192);
ByteArrayBuffer buff = new ByteArrayBuffer(64);
int current = 0;
while ((current = bis.read()) != -1) {
buff.append((byte)current);
}
byte[] imageData = buff.toByteArray();
bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
try {
is.close();
is = null;
} catch (IOException e) {
}
BTW, see this post, it should work also
My current Android application downloads a number of audio files. When I employ this code to execute the download I get file not found exception:
try {
final URL downloadFileUrl = new URL("http://filelocation/url.m4a");
final HttpURLConnection httpURLConnection = (HttpURLConnection) downloadFileUrl.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.connect();
mTrackDownloadFile = new File(Record.this.getCacheDir(), "mediafile");
mTrackDownloadFile.createNewFile();
final FileOutputStream fileOutputStream = new FileOutputStream(mTrackDownloadFile);
final byte buffer[] = new byte[16 * 1024];
final InputStream inputStream = httpURLConnection.getInputStream();
int len1 = 0;
while ((len1 = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len1);
}
fileOutputStream.flush();
fileOutputStream.close();
} catch (final Exception exception) {
Log.i(TAG, "doInBackground - exception" + exception.getMessage());
exception.printStackTrace();
mTrackDownloadFile = null;
}
When i employ this code it works fine:
try {
final URL downloadFileUrl = new URL("http://filelocation/url.m4a");
final URLConnection urlConnection = downloadFileUrl.openConnection();
mTrackDownloadFile = new File(PlayOpponent.this.getCacheDir(), "mediafile");
mTrackDownloadFile.createNewFile();
final FileOutputStream fileOutputStream = new FileOutputStream(mTrackDownloadFile);
final byte buffer[] = new byte[16 * 1024];
final InputStream inputStream = urlConnection.getInputStream();
int len1 = 0;
while ((len1 = inputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len1);
}
fileOutputStream.flush();
fileOutputStream.close();
} catch (final Exception exception) {
Log.i(TAG, "doInBackground - exception" + exception.getMessage());
exception.printStackTrace();
mTrackDownloadFile = null;
}
Can someone please point out where I am going wrong?
According to this blog removing
httpURLConnection.setDoOutput(true);
in your code may solve the problem. It's said to be a ICS issue.
I've made I simple function to write from URL to file. Everything works good until out.write(), I mean there's no exception, but it just doesn't write anything to file
Here's code
private boolean getText(String url, String name) throws IOException {
if(url!=null){
FileWriter fstream = new FileWriter(PATH+"/"+name+".txt");
BufferedWriter out = new BufferedWriter(fstream);
URL _url = new URL(url);
int code = ((HttpURLConnection) _url.openConnection()).getResponseCode();
if(code==200){
URLConnection urlConnection = _url.openConnection(); //
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) != -1) {
String chunk = new String(buffer, 0, bytesRead);
out.write(chunk);
}
return true;
}
out.close();
}
return false;
}
Can someone tell me what's wrong please?
Try fstream.flush().
Also out.close() should be called before returning from a function.
I have tried three ways of downloading images. All suggest by members of Stackoverflow .
All the three methods fail to download all the images from the server. Few are downloaded and few are not.
I noticed a thing that each of the method fail to download image from particular position.
That is method 3 always fails to download the first three images. I changed the images but even then , the first three images are not downloaded.
Method 1:
public Bitmap downloadFromUrl( String imageurl )
{
Bitmap bm=null;
String imageUrl = imageurl;
try {
URL url = new URL(imageUrl); //you can write here any link
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
bm= BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.toByteArray().length);
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
return bm;
}
Here the error i get for missed images is :SKIimagedecoder , the factory returned null.
Method: 2
public static Bitmap loadBitmap(String url)
{
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), 4*1024);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 4 * 1024);
int byte_;
while ((byte_ = in.read()) != -1)
out.write(byte_);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
System.out.println(e);
Log.e("","Could not load Bitmap from: " + url);
} finally {
try{
in.close();
out.close();
}catch( IOException e )
{
System.out.println(e);
}
}
return bitmap;
}
The error i get here is same as above.
Method 3:
private Bitmap downloadFile(String fileUrl){
URL bitmapUrl =null;
Bitmap bmImg = null;
try {
bitmapUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpGet httpRequest = null;
try {
httpRequest = new HttpGet(bitmapUrl.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream instream = bufHttpEntity.getContent();
bmImg = BitmapFactory.decodeStream(instream);
} catch (Exception e) {
System.out.println(e);
}
return bmImg;
}
The error i get here is : org.apache.http.NoHttpResponseException: The target server failed to respond.
please help. It is the only thing stopping me from completing the project.
Take a look at this.. Clearly explained about image download from the Server..Image from Server....
I'm assuming you are downloading the images to display rather than just save on the device. If this is the case, I recommend looking into using Droid-Fu, more specifically WebImageView. You can just pass the URL to the WebImageView and it will load the image as it can, which will avoid having an image fail to load because of the connection timing out, which I'm guessing is the problem you are having.
In XML:
<com.github.droidfu.widgets.WebImageView
android:id="#+id/image"
android:layout_width="70dip"
android:layout_height="70dip"
droidfu:autoLoad="true"
droidfu:progressDrawable="..."
/>
In Code:
WebImageView image = (WebImageView) convertView.findViewById(R.id.image);
image.setImageUrl(image_url);
image.loadImage();
It's possible that your creation of bitmaps takes time and therefore the connection times out. You could possibly get references to all the inputstreams and then download and create. This is a rough-cut answer, but if the reasoning is right, you can improve on it:
public Bitmap[] downloadFromUrl(String[] imageUrls)
{
Bitmap[] bm = new Bitmap[imageUrls.length];
BufferedInputStream[] bis = new BufferedInputStream[imageUrls.length];
for (int i = 0; i < imageUrls.length; i++)
{
try
{
URL url = new URL(imageUrls[i]); // you can write here any link
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
bis[i] = new BufferedInputStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
}
for (int i = 0; i < bis.length; i++)
{
try
{
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis[i].read()) != -1)
{
baf.append((byte) current);
}
bm[i] = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.toByteArray().length);
}
catch (IOException e)
{
e.printStackTrace();
}
}
return bm;
}