Not able to Load Image from Server in android - java

Here I am trying to download a image from server. But it is always throwing Exception. Can any One tell me Why it is Happening and what will be the Correct way?
public static String getBitmap(String url) throws IOException {
InputStream is = (InputStream) new URL(url).getContent();
Bitmap bmp= BitmapFactory.decodeStream(is);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] b=stream.toByteArray();
String encoded = Base64.encodeToString(b, Base64.DEFAULT);
is.close();
return encoded;
}

Please try this functions get bitmap and download the bitmap
Bitmap bitmap = getBitmapfromUrl(imageurl);
imageview.setImageBitmap(bitmap);
SaveImage(bitmap);
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n;
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And Add this permision in your manifest file

Call this function from your activity and get inputStream. After getting inputStream (Bitmap bitmap = Bitmap.decodeStream(inputStream));
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
throw new IOException("Error connecting");
}
return in;
}

Try using Glide or Picasso image processing library.
here is Glide demo
Glide.with(this).load(YourImageURL)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(Imageview);
and add this dependency in gradle.
compile 'com.github.bumptech.glide:glide:3.7.0'
you can also set placeholder while image loading. its like alt attribute in html
Glide.with(this).load(YourImageURL)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.placeholder(R.drawable.backimage)
.into(Imageview);
Here is Picasso demo
Picasso.with(context).load(url).placeholder(R.drawable.user_placeholder)
.error(R.drawable.user_placeholder_error)
.into(imageView);
and add this dependency:
compile 'com.squareup.picasso:picasso:2.5.2'
these lib also provide cache feature so you don't need to load second time.

Related

Download image from Android using HttpConnection got 410, but postman got 200

I face a problem during downlonading an image in Android.
The problematic image link:
https://via.placeholder.com/150/92c952
I can use postman to download the image successfully (200).
But when I code in Android, using HttpConnection, it responds me with error status code 410.
(And then triggers FileNotFounedException.)
Below is my code,
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int bytesRead = -1;
byte[] buffer = new byte[1024];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
httpConn.disconnect();
return outputStream.toByteArray();
} else {
httpConn.disconnect();
throw new RuntimeException("Error code: " + responseCode);
}
My code can successfully download images from Imgur, but as for this link, it fails.
Please share any idea, I do appreciated a lot!
It's quite a simple reason.
The cause is not at your Java program side but at the server side.
The server rejects your connection by responding HTTP 410 Gone.
To dodge the server's behavior, just set any popular User-Agent string on your request before doing actual request.
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X; ja-JP-mac; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6"
);
int responseCode = httpConn.getResponseCode();
...
if you wanna download image and show it on ImageView you can use glide or picasso. its pretty easy to implement, on glide you can just
Glide.with(context).load("https://via.placeholder.com/150/92c952").into(myImageView);
Use this method to download image from URL
// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... URL) {
String imageURL = URL[0];
Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
// set this bitmap to image view
// NOW USE THIS BITMAP TO SAVE IMAGE IN MEMORY, I SAVED IN INTERNAL MEMORY
if (result != null) {
File destination = new File(getActivity().getCacheDir(),
"profile" + ".jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
selectedFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Now call this method like this
new DownloadImage().execute("https://via.placeholder.com/150/92c952");

Download a image from server to android and show in imageview

I have an server (i use GlassFish). I am able to send Json or XML etc. with http to my android device. I saw an example to upload a picture from my android device to the server. That converts my picked image to byte, converts to String and back at my server. So i can put it on my PC (server).
Now i just want the opposite: get a picture from my PC and with the URL get the image (bitmap here) to imageview. but with debugging bmp seems to be "null". google says its because my image is not a valid bitmap (so maybe something is wrong at my server encoding?).
What does i need to change to this code to get it working?
Server code:
public class getImage{
String imageDataString = null;
#GET
#Path("imageid/{id}")
public String findImageById(#PathParam("id") Integer id) {
//todo: schrijf een query voor het juiste pad te krijgen!
System.out.println("in findImageById");
File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");
try{
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = Base64.encodeBase64URLSafeString(imageData);
imageInFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return imageDataString;
}
}
and this is the android side (android studio):
public class XMLTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
java.net.URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String line) {
super.onPostExecute(line);
byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
try {
Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
ivFoto.setImageBitmap(bmp);
}catch (Exception e){
Log.d("tag" , e.toString());
}
}
}
Have you tried HttpURlConnection?
Here's a sample code:
private class SendHttpRequestTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL("http://xxx.xxx.xxx/image.jpg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}catch (Exception e){
Log.d(TAG,e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
ImageView imageView = (ImageView) findViewById(ID OF YOUR IMAGE VIEW);
imageView.setImageBitmap(result);
}
}
I hope i could help
You can use Glide it is simplest way to load image
This is how you can save image
Glide.with(context)
.load(image)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
String name = new Date().toString() + ".jpg";
imageName = imageName + name.replaceAll("\\s+", "");
Log.d(TAG, "onResourceReady: imageName = " + imageName);
ContextWrapper contextWrapper = new ContextWrapper(mContext);
File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory, imageName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(myPath);
resource.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
and this is how you can read the image
ContextWrapper contextWrapper = new ContextWrapper(mContext);
File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
String path = directory.getAbsolutePath();
path = path + "/" + imageName;
Glide.with(mContext).load(path).into(your imageview);
Why don't you use Glide?
For build.gradle in your app module:
dependencies {
compile 'com.github.bumptech.glide:glide:3.7.0'
...
}
Then:
Glide
.with(context) // replace with 'this' if it's in activity
.load("http://www.google.com/.../image.gif")
.into(R.id.imageView);
Try using Base64.encodeBase64String(imageData) with out using the URLSafeString.
If there are people who are also trying to do it my way, this is working:
public class XMLTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
java.net.URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String line) {
super.onPostExecute(line);
byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
try {
Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
ivFoto.setImageBitmap(bmp);
}catch (Exception e){
Log.d("tag" , e.toString());
}
}
}
#Stateless
#Path("getImage")
public class getImage {
//todo: capture error inandroid + take just path!
String imageDataString = null;
#GET
#Path("imageid/{id}")
public String findImageById(#PathParam("id") Integer id) {
//todo: schrijf een query voor het juiste pad te krijgen!
System.out.println("in findImageById");
File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");
try{
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = Base64.encodeBase64String(imageData);
imageInFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return imageDataString;
}
}
I hope this code is useful.
go to your MainActivity.java and try this code:
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public void downloadImage(View view)
{
Log.i("Button","Tapped");
DownloadImage task = new DownloadImage();
Bitmap result = null;
try {
result = task.execute("https://vignette.wikia.nocookie.net/disney/images/0/0a/ElsaPose.png/revision/latest?cb=20170221004839").get();
}
catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
imageView.setImageBitmap(result);
}
public class DownloadImage extends AsyncTask<String, Void, Bitmap>
{
#Override
protected Bitmap doInBackground(String... imageurls) {
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(imageurls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream in =httpURLConnection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in);
return myBitmap;
}
catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView);
}
}
Don't forget to add this piece of code in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>

Share Image Not working Android 6.0

I have one android application which have share image function as well save image. This functions are working fine in other than android 6.0 . When I try to share image with whatsapp as well other application, image does not getting attached. My java code for share image like below. What Should I correct for solve the issue ?
Thanks Friends for support :)
protected String doInBackground(String... args) {
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath.getAbsolutePath() + "/Hindi Picture/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file.getAbsolutePath()));
startActivity(Intent.createChooser(share, "Share Image"));
pDialog.dismiss();
}
});
}

Read external image in Android

I trying read a external imagen but I've the error
"android.os.NetworkOnMainThreadException" and
"http.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)"
OnCreate
imageView = (ImageView) findViewById(R.id.image_view);
downloadFile(imageHttpAddress);
Function downloadFile
void downloadFile(String imageHttpAddress) {
URL imageUrl = null;
try {
imageUrl = new URL(imageHttpAddress);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.connect();
loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
imageView.setImageBitmap(loadedImage);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error cargando la imagen: "+e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
From Android docs
You should not perform network operations on the UI thread.
To avoid this exception, you can use AsyncTask for your request.
imageView = (ImageView) findViewById(R.id.image_view);
new AsyncTask<String, Void, Bitmap>(){
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Bitmap doInBackground(String... url) {
return downloadFile(url[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
imageView.setImageBitmap(bitmap);
}
}.execute(imageHttpAddress);
private Bitmap downloadFile(String imageHttpAddress) {
URL imageUrl = null;
try {
imageUrl = new URL(imageHttpAddress);
HttpURLConnection conn =(HttpURLConnection)imageUrl.openConnection();
conn.connect();
loadedImage = BitmapFactory.decodeStream(conn.getInputStream());
return loadedImage;
} catch (IOException e) {
e.printStackTrace();
}
}
Even better, use some Async image handling library for android. there are many of these around the internet. A very popular one is picasso
You can use this function ;)
public Bitmap DownloadImage(String STRURL) {
Bitmap bitmap = null;
InputStream in = null;
try {
int response = -1;
URL url = new URL(STRURL);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}catch(Exception ex) {
throw new IOException("Error connecting");
}
bitmap = BitmapFactory.decodeStream(in);
in.close();
}catch (IOException e1) {
e1.printStackTrace();
}
return bitmap
}

Servlet reply to getHttpConnection

I have some images in my Servlet that I want to download into my Android app.
I am performing a GET request to this URL:
public static final String URL ="http://myIpAddress:8080/imgs";
And this class doing the job:
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
StaggeredPrenotaTour staggeredPrenotaView;
public GetXMLTask(StaggeredPrenotaTour listView){
this.staggeredPrenotaView = listView;
}
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
staggeredPrenotaView.pullTours(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
and in my Servlet:
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
InputStream st = getServletContext().getResourceAsStream("/WEB-INF/imgs/cardbackground9.jpg");
BufferedImage bi = ImageIO.read(st); **//error here**
OutputStream out = resp.getOutputStream();
//Todo send InputStream into OutputStream
ImageIO.write(bi, "jpg", out);
out.close();
}
I would like to receive an InputStream containing my Bitmap image but I receive the following error:
WARNING: Error for /imgs
java.lang.NoClassDefFoundError: javax.imageio.ImageIO is a restricted class.Please see the Google App Engine developer's guide for more details.
at com.google.appengine.tools.development.agent.runtime.Runtime.reject(Runtime.java:51)
at madapps.bicitourbo.backend.MyServlet.doGet(MyServlet.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
...
Why do you need to use ImageIO? You can do simply something like:
InputStream st = getServletContext().getResourceAsStream("/WEB-INF/imgs/cardbackground9.jpg");
OutputStream os = resp.getOutputStream();
if (st != null) {
byte[] buf = new byte[4096];
int nRead;
while( (nRead=st.read(buf)) != -1 ) {
os.write(buf, 0, nRead);
}
st.close();
}

Categories