Display an image scraped from a website in jsoup - java

I'm making a small application in Java that requires me to scrape an image from a website and display it in a GUI. Now I'm not asking how to get the image's absolute URL, I'm asking how I can display it once I've gotten the absolute URL. I'm using the jsoup library as the web scraper.

I used the following piece of code to get the desired output shown in the image below (Use appropriate imports):
BufferedImage myPicture = null;
try {
URL url = new URL("https://www.w3schools.com/css/img_fjords.jpg");
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "MyAppName");
myPicture = ImageIO.read(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
frame.getContentPane().add(picLabel);
For setRequestProperty, use any string in place of MyAppName, it's just a value to the User-Agent attribute in the http request made by your app
Reference Image

Related

How to concat an object name as part of a file path?

I'm trying to make an application to manage some drink recipes...
I need to show the drink image in a JPanel already working with the file path like this:
ImageIcon image = new ImageIcon("src/fotos/trinidad.jpg");
The problem is that when I try to set this path setting it with the object name, the image is not being loaded.
String s = ("src/fotos/"+b.getNome().toLowerCase()+".jpg");
ImageIcon image = new ImageIcon(s);
Printing this string s I have this result:
System.out.println(s);
src/fotos/trinidad.jpg
Apparently it looks the same path, but the image is not being loaded.
What am I doing wrong?
Try something like this, if the image (path) does not exist you can catch the exception and treat accordingly.
BufferedImage drinkImage = null;
try {
drinkImage= ImageIO.read(new File("src/fotos/trinidad.jpg"));
} catch (IOException e) {
// TODO
e.printStackTrace();
}
ImageIcon image = new ImageIcon(drinkImage);
// Put image in your JPanel

Image loaded from a PHP script isn't displayed in ImageView

I want to fill an ImageView with an image saved on my localhost. I can display it in a browser fine but it doesn't get displayed in my ImageView.
PHP script to display image:
<?php
include('connect_db.php');
$id = $_GET['id'];
$path = 'Profile_Images/'.$id.'.jpg';
echo '<img src='.$path.' border=0>';
?>
Here is my android code to download an image from a URL:
URL url;
try {
url = new URL("http://192.168.1.13/get_profile_image.php?id=145");
new DownloadImage(this).execute(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void imageDownloaded(final Bitmap downloadedImage) {
runOnUiThread(new Runnable() {
public void run() {
ImageView imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(downloadedImage);
}
});
}
When I put the URL to some other image it works fine but mine never gets loaded, any ideas?
Also, the following code works but I have a feeling its bad practice..
URL url;
try {
url = new URL("http://192.168.1.13/Profile_Images/145.jpg");
new DownloadImage(this).execute(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Where 145 would be a variable.
Edit
Any reasons for the down-votes would be appreciated!
It's pretty simple, actually. When you send a request to http://192.168.1.13/get_profile_image.php?id=145 a string (<img src=Profile_Images/'.$id.'.jpg border=0>) is sent back. Because the DownloadImage class doesn't parse HTML (it wants raw image data) it doesn't know where the actual image is. Two solutions:
Your 'bad practice' approach
Use this PHP script instead to echo the raw image data:
PHP:
$id = $_GET['id'];
$path = 'Profile_Images/'.$id.'.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($path));
readfile($path);
EDIT: forgot to credit someone: the above code is taken from here (with adapted variable names): https://stackoverflow.com/a/1851856/1087848
Your PHP code will print out something along the lines of:
<img src=Profile_Images/145.jpg border=0>
Not only is this malformed HTML, but it is a text output. Your other URL, http://192.168.1.13/Profile_Images/145.jpg points to an image file, from which the data your receive is an image, not an HTML string.
You should consider having your PHP return a JSON response with the URL of the image ID, and then running DownloadImage on that URL. The advantage this has over a raw echo is that you can easily expand the solution to return other types of files, and even return an array of files.

Access Client clipboard from server in java/jsf/primefaces

Problem description : user press print screen button and then click on paste button on application. That image will be store on server.
I googled and find answer on Stack over and used following code
public Image getImageFromClipboard()
{
Clipboard systemClipboard = (Clipboard) AccessController.doPrivileged(new PrivilegedAction() {
public Object run()
{
Clipboard tempClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
return tempClipboard;
}
});
// get the contents on the clipboard in a
// Transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if contents are empty, if so, return null
if (clipboardContents == null)
return null;
else
try
{
// make sure content on clipboard is
// falls under a format supported by the
// imageFlavor Flavor
if (clipboardContents.isDataFlavorSupported(DataFlavor.imageFlavor))
{
// convert the Transferable object
// to an Image object
Image image = (Image) clipboardContents.getTransferData(DataFlavor.imageFlavor);
return image;
}
} catch (UnsupportedFlavorException ufe)
{
ufe.printStackTrace();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
/*try {
Robot robot;
robot = new Robot();
final GraphicsConfiguration config
= GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
final BufferedImage screenshot = robot.createScreenCapture(config.getBounds());
return screenshot;
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
return null;
}
This code work well if application is running on my machine and I press Print Screen. Image is available and store.
My problem is that when I am deploying this application on separate server and run application on another machine. When user press Print screen and then click on button in application. Server won't find any image because it look on clipboard and on server clipboard no image is available. Image is available on Client desktop clipboard.
Kindly help me to access Client clipboard from server using JSF/primefaces. Or other alternative way.
I am using primefaces 3.4, server is weblogic 10.3.5.
If your application will be running on different browsers, you will find no 100% reliable way of doing it unless you implement some specific component with some other technology like Flash.
I would really use the approach of saving the image and uploading it to the server via a normal file upload form. Else you will be having headaches with Browser security issues.
Regards

Decoding Bitmap stream failed

I'm trying to work my through "Sam's Teach Yourself Android Application Development in 24 Hours" and have become stuck in hour 12. The problem appears to be in this section:
private Drawable getQuestionImageDrawable(int questionNumber) {
Drawable image;
URL imageUrl;
try {
// Create a Drawable by decoding a stream from a remote URL
imageUrl = new URL(getQuestionImageUrl(questionNumber));
InputStream stream = imageUrl.openStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
image = new BitmapDrawable(getResources(), bitmap);
} catch (Exception e) {
Log.e(TAG, "Decoding Bitmap stream failed");
image = getResources().getDrawable(R.drawable.noquestion);
}
return image;
}
The questionNumber and getQuestionImageUrl() have been tested and are returning what I believe are the correct values(1 and http://www.perlgurl.org/Android/BeenThereDoneThat/Questions/q1.png). There is an image at that url, but I always get the exception. I have tried several variations but when none of them worked I went back to this code from the book. What am I doing wrong here?
I'm new to java and android, so I'm probably missing something simple. I have had many other problems with the code in the book and the updated code from the website (all of which have been solved either here or with developer.android.com). This is my first question, so if I failed to provide any information please let me know.
I would do the following and it might work:
private Drawable getQuestionImageDrawable(int questionNumber) {
Drawable image;
URL imageUrl;
try {
// Create a Drawable by decoding a stream from a remote URL
imageUrl = new URL(getQuestionImageUrl(questionNumber));
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(stream);
image = new BitmapDrawable(getResources(), bitmap);
} catch (Exception e) {
Log.e(TAG, "Decoding Bitmap stream failed");
image = getResources().getDrawable(R.drawable.noquestion);
}
return image;
}
Make sure you do this kind of heavy operations in a background thread insteaad of the main one and had INERNET permission to your application's manifest.
Let me know about your progress.
Probably the exception is because you are making a network connection form the app ui thread. That works on older Android versions but not in the newer.
Take a look to Android network operation section.
The main thing to do is use an AsyncTask

How to send an image from Java-serverside, and handle it on JQuery-clientside

I want to rescale an image and return it to the client, and am running into some trouble with sending the image back to the client.
My serverside controller:
#RequestMapping(value = {"/fw/ajax/submit_profileimage.do"})
public void submitFile(HttpServletRequest request, HttpServletResponse response, #RequestParam("file") MultipartFile f) {
try {
InputStream in = new ByteArrayInputStream(f.getBytes());
BufferedImage originalImage = ImageIO.read(in);
BufferedImage newImage = new BufferedImage(MAX_HEIGHT, MAX_WIDTH, BufferedImage.TYPE_INT_RGB);
paintComponent(newImage.getGraphics(), originalImage, getRatio(originalImage));
ImageIO.write(newImage, "png", response.getOutputStream());
response.setContentType("image/png");
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Clientside Jquery code:
uploadButton.click(function(){
$('#imagePreview').addClass('loading');
form.ajaxSubmit(function(data){
alert(data); //this is where I'd like to handle the image!
});
});
the data that is returned by the ajaxSubmit is:
"<body style="margin: 0px;"><img style="-webkit-user-select: none" src="http://localhost:8080/fairview/ajax/submit_profileimage.do"></body>"
Clearly not an image file.
But when I check the debugger, I can see that the submit_profileimage.do request has succeded, and allegedly returned an image! I have no idea if I've done something wrong on the clientside, or on the serverside.
So the question is: How can I display the image on the clientside?
I would simply save the resized image on the server and return back to jquery simpy a URL to where the resized image has been saved. Then simply set the src attribute of the image to that URL. The browser will than take care of downloading the image.
uploadButton.click(function(){
$('#imagePreview').addClass('loading');
form.ajaxSubmit(function(data){
//Assuming data is the URL to the resized image.
$("#myimage").attr("src", data);
});
});
I went with the approach described as the accepted answer here: Help getting image from Servlet to JSP page
Which pretty much means I didn't really answer the initial question, I still can't handle a raw image clientside. Rather, I use one service to store the image, return the id of where the image is stored, and set the src attr of the image to a service that will return the image.

Categories

Resources