Good day,
I'm trying to retrieve an image using Jsoup but I'm unsure as to what exactly I should be getting from the website. I've used the following code to read from the website and have been able to get the images particular title and the URL it links to but not the image.
I want to set this image to the ImageView that I have in the activity. Here's my code thus far:
// Get the required stuff from the webpage
Document document = null;
try {
document = Jsoup.connect(URL).get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Element info = document.select("div.featurebox").first();
// Caption on image
docInfo = info.text();
// URL of image
imageURL = info.attr("data-url");
// Retrieve the actual image
Element featureImage = document.select("div.featurebox-image").first();
// Unsure what to get here
It should be noted that the image isn't stored as a normal img-src way. The particular div class I'm looking at is this:
<div class="featurebox-image" style="background:url(http://img.mangastream.com/cdn/feature/02.jpg) center center;">
<div class="featurebox-caption">
<strong>History's Strongest Disciple Kenichi <em>544</em></strong> - Witch </div>
</div>
So I'm after the actual image from that URL.
How do i go about this?
Thanks
Thanks to Hardip Patel for providing the start. Here is what I did:
I took Hardips code and changed it to the following:
Element featureImage = document.select("div.featurebox-image")
.first();
String temp = featureImage.getElementsByAttribute("style")
.toString();
// URL of image
imageStrg = temp
.substring(temp.indexOf("(") + 1, temp.indexOf(")"));
After that it took alittle looking about StackOverflow to find out how to set it. I initially tryed to set it using the URL using the setImageURI() method, but that was throwing an error. See here for why. Instead I used that SoH's answer to create a bitmap from the URL:
// Method to return a bitmap from an images URL
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
// See what we are getting
Log.i(TAG, "" + url);
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
After that I just had to set the Bitmap from earlier and update the image view using the ASyncTask's onPostExecute() method:
imageOne = getImageBitmap(imageStrg);
#Override
protected void onPostExecute(String result) {
// Write the result (document title) to the textview
super.onPostExecute(result);
// Update the textview with results
if (result == null) {
txtVwDocTitleValue.setText("Nothing to report...");
} else {
txtVwDocTitleValue.setText(result);
txtVwDocURLValue.setText(imageURL);
// Set the views image
imgVwManga1.setImageBitmap(imageOne);
}
// Destroy the progress bar
stopProgressDialog();
}
Cheers all!
See if this works :-
String temp = featureImage.getAttribute("style");
String url = temp.substring(temp.indexOf("(")+1,temp.indexOf(")"));
Try this
Document doc = Jsoup.connect("www.mywebsite.com").get();
Elements images = doc.select("img[src~=(?i)\.(png|jpe?g|gif)]");
Related
I would like to present an image that comes from an internal image server of the company. I can access it by an internal http address. Must present it without showing this internal address in the source code, using a p.graphicImage .
The View is here:
<p:fieldset legend="Dados pessoais">
<br/>
<p:graphicImage value="#{funcionarioEditMB.graphicText}" id="foto" cache="false">
<f:param name="id" value="#{funcionarioEditMB.bean.matricula}" />
</p:graphicImage>
<br/>
//--*-
MB related part:
//no init chamo esta função passando a matricula (this.getImagem(funcionario.getMatricula());)
public void getImagem(Integer matricula){
ByteArrayOutputStream os = null;
byte[] bytes = null;
FacesContext context = FacesContext.getCurrentInstance();
String id = context.getExternalContext().getRequestParameterMap().get("id");
try{
URL url = new URL(funcionarioBC.getImage(Integer.parseInt(id)));
BufferedImage image = ImageIO.read(url);
os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
bytes = os.toByteArray();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
// So, we're rendering the view. Return a stub StreamedContent so that it will generate right URL.
graphicText = new DefaultStreamedContent();
} else {
// So, browser is requesting the image. Get ID value from actual request param.
graphicText = new DefaultStreamedContent(new ByteArrayInputStream(bytes));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private StreamedContent graphicText;
public StreamedContent getGraphicText() {
return graphicText;
}
But the image does not appear in the view. The following link is displayed:
http://localhost:8080/eSGRH/javax.faces.resource/dynamiccontent.properties.jsf?ln=primefaces&pfdrid=aiHZO8v7zFQ6p%2bPffO1S1vWT2KGBHKr%2bR3guIqtplAUT4IpnxJZmHw==&id=479488&pfdrid_c=false&uid=4e51fb92-b0bc-4530-8e3c-3d28fa750563
Could someone help me to understand what is wrong?
OK, so I'm writing an Android app, and am trying to download a Bitmap and set it as an ImageView. The code is below for the relevant parts:
private class GetContactInfo extends AsyncTask<String, Void, ContactInfo[]> {
#Override
protected ContactInfo[] doInBackground(String... url) {
// Instantiate what is needed
URL json = null;
//Set the JSON URL
try {
json = new URL(url[0]);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
// Use Jackson library to read out the data from the contacts page
try {
contacts = mapper.readValue(json, ContactInfo[].class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Add everything into the bitmap ArrayList
for (int i = 0; i < contacts.length; i++) {
String imageURL = contacts[i].getSmallImageURL();
// Download the Bitmap and add it to the ArrayList
try {
bitmap.add(downloadBitmap(imageURL));
} catch (IOException e) {
e.printStackTrace();
}
}
// Return statement
return contacts;
}
public Bitmap downloadBitmap(String imageURL) throws IOException {
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream stream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
if (bitmap == null) {
Log.e("Null", "Bitmap null");
}
return bitmap;
}
The log never catches that bitmap is null, or at least it doesn't show it (I see in the stack trace that there are 4 more errors, but they never show up and I'm not sure how to expand it to show the other errors.)
The NullPointerException comes at the bitmap.add(downloadBitmap(imageURL)); line. So somehow my downloadBitmap function is returning a null result. Any ideas?
Edit: I'm not sure if this matters, but the images in the URLs are .jpeg files.
Edit 2: Put this in the comments so I will edit it into my post as well, bitmap is declared as a Global Variable like so ArrayList<Bitmap> bitmap; This is so I can later use it in my onPostExecute method.
As you said the error is at line
bitmap.add(downloadBitmap(imageURL));
which means culprit is your bitmap variable and not downloadBitmap(imageURL) method.
Also, in your edit you have mentioned that you have declared bitmap as a global variable - ArrayList bitmap;
In order to access(add bitmap onjects to it) this globally declared variable you must initialize it.
In your onCreate do -
bitmap = new ArrayList<Bitmap>();
and the NPE must go.
While you are downloading images from the Internet, you should use an async request. In downloadBitmap the connection is downloading in another thread, but the main thread has returned bitmap immediately, whether or not the downloading is accomplished.
Where did you initialized bitmap? As far as I can tell, it is null and you are using that null object, so Null Pointer Exception come out. That's from the information you provided. If the error is occurred inside the function, it's the different matter.
Here is my code i have written to get images from assets folder by passing imagename from database.But when passedImage name is not found in assets folder then i want to show some dummy images my code is throwing only catch block when no image is found but its not showing default image and no log is print in case of image not found .....
private Bitmap getBitmapFromAsset(String strName) {
AssetManager assetManager = getAssets();
InputStream istr = null;
Bitmap bitmap = null;
try {
istr = assetManager.open(strName);
if(istr.equals("null"))
{
Log.i("getBitmapFromAsset isStr",""+istr);
bitmap = BitmapFactory.decodeStream(assetManager.open("save_fatwa.jpg"));
}
else
{
bitmap = BitmapFactory.decodeStream(istr);
}
} catch (Exception e) {
Log.i("getBitmapFromAsset",""+bitmap);
e.printStackTrace();
}
return bitmap;
}
AssetManager.open returns an InputStream, not a string. If should be if(istr==null) not if it equals the string "null".
I am using Jsoup to scrape a gallery of pictures from this italian website
http://www.italiaebraica.org/index.php?option=com_phocagallery&view=category&id=3:famiglia-levi&Itemid=143&lang=it
in an AsyncTask with Jsoup i'm getting from the HTML all the urls of the images:
#Override
protected Void doInBackground(String... params) {
Document doc;
try {
ConnectivityManager conMgr = (ConnectivityManager) mActivity
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
doc = Jsoup
.connect(urlReceivedToConnect)
.timeout(0).get();
Elements imgList = doc.getElementsByClass("phocagallery-box-file-third").select("img");
photoList = new ArrayList<String>();
ListIterator<Element> post = imgList.listIterator();
while (post.hasNext()) {
photoList.add(post.next().attr("abs:src"));
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Then, in a costumized adapter, i'm taking this urlsList and i'm loading the images from the url that i'm putting in a gridView later:
private Drawable LoadImageFromURL(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
The problem is: some of the pictures are shown and are ok, but some others presents this error:
06-23 10:06:06.930: I/System.out(493): java.io.FileNotFoundException: http://www.italiaebraica.org/images/phocagallery/famiglia_levi/thumbs/phoca_thumb_m_Famiglia Levi 024.jpg
what's the problem? how can I get all the pictures in the right way?
Please help,
hope it is clear ,
i'm a junior developer!!
java.io.FileNotFoundException:
is pretty self-explanatory. Print out the urls so you can see the ones that cause the exception. It shouldn't take too long to debug.
I'm don't know what images exist and what don't, so you're the one who has to figure it out.
What is wrong is there are spaces in the URL. Most browsers are made to detect if there is a space and replace it with %20 so you won't get any error going to the URL in a browser. So I would recommend using:
private Drawable LoadImageFromURL(String url) {
if(url.contains(" ")){
url.replace(" ", "%20");
}
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
I am trying to download image from server. Few are downloading and few and creating problem. I don't know why.
I have downloaded and show image to user on the same location. Here is the file which is able to download.
http://www.mongreldog.co.nz/unilogo/Backgrounds_20399.png
When I am trying to download following image. This image is opening in browser but not downloading in android
http://www.mongreldog.co.nz/unilogo/Twitter-Ryan_Giggs_Imogen_Thomas_Guard-Footballer_Affair_UK_Manchester%20United_M_785.jpg
Its give exception
java.io.FileNotFoundException: http://www.mongreldog.co.nz/unilogo/Twitter-Ryan_Giggs_Imogen_Thomas_Guard-Footballer_Affair_UK_Manchester United_M_785.jpg
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:521)
at src.com.mongreldog.appsupport.Utils.downloadImage(Utils.java:77)
at src.com.mongreldog.ViewFullCompAndCommentActivity$3.performInBackground(ViewFullCompAndCommentActivity.java:607)
at src.com.mongreldog.appsupport.HeavyWorker.doInBackground(HeavyWorker.java:44)
at src.com.mongreldog.appsupport.HeavyWorker.doInBackground(HeavyWorker.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
Here is my code.
public static Bitmap downloadImage(String imageURLStr) {
Bitmap bitmap = null;
InputStream in = null;
try {
URL url = new URL(imageURLStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
in = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (SocketTimeoutException e) {
bitmap = null;
e.printStackTrace();
} catch (IOException e) {
bitmap = null;
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
bitmap = null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
bitmap = null;
}
return bitmap;
}
Use URL Encoder to encode the image URL, as you can see the URL have white spaces in the log report.
public static Bitmap downloadImage(String imageURLStr) {
imageURLStr = URLEncoder.encode(imageURLStr, "utf-8");
//... rest of your code.
}
Edit: as you reported of issue '+' instead of %20
you can use
public static Bitmap downloadImage(String imageURLStr) {
imageURLStr = imageURLStr.replaceAll(" ", "%20");
//... rest of your code.
}
For source check here
I try to use URLEncoder.encode() to encode the URL. Its strange that it convert " " with "+".
Please try Uri.encode(imageURL). I just try it and its working perfectly.
I have tested that in android.
Looks like the file name is not being parsed correctly (the space between 'Manchester' and 'United').
Use URLEncoder.encode() to encode the URL.
Your second URL is very instable. It may return 404 in the most cases even in Chome. I have seen the picture only once.