retrieve single image via its url in java - java

I have a problem and I hope that you can help me. I would appreciate any help from anyone. The problem is the following.
I have a camera that has an http service, and I am communicating with the camera using the http. So the problem is that I send http request and I have back an http response in which I have a binary jpeg data. But I do not know how to convert that data into picture.
So my question is how can I convert that binary data into picture with java?
This is one example
http request:
GET (url to picture)
http response:
binary jpeg data
I thank to all of you in forward for all of your help.
URL url = new URL("http://10.10.1.154" + GETIMAGESCR());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
// while ((inputLine = in.readLine()) != null){
// inputLine = in.readLine();
File file = new File("D:\\alphas\\proba.bin");
boolean postoi = file.createNewFile();
FileWriter fstream = new FileWriter("D:\\alphas\\proba.bin");
BufferedWriter out = new BufferedWriter(fstream);
while ((inputLine = in.readLine()) != null){
out.write(in.readLine());
// out.close();
// System.out.println("File created successfully.");
System.out.println(inputLine);
}
System.out.println("File created successfully.");
out.close();
in.close();
With this code I am getting the binary JPEG data, and I menage to save the data in a file. So the question is now how to convert this data into picture, or how to create the picture?
By the way I do not need to save the file that I get, if you have a way to create the picture directly it would be the best way
retrieve single image via its url in java

you just need to write byte data of image in response and set the proper content type, It will serve image from servlet

try {
URL url = new URL("http://site.com/image.jpeg");
java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().createImage(url);
} catch (MalformedURLException e) {
} catch (IOException e) {
}

Am I missing something or are you just looking for this:
new ImageIcon(new URL("http://some.link.to/your/image.jpg"));
If you need to save the data from the URL, then just read the bytes from the corresponding InputStream and write the read bytes to a FileOutputStream:

Related

JAVA image request from multipart-form

I'm trying to redesign my code that originally took in JSON POST. To now take in images from POST requests. The problem is that when trying to debug it keeps giving me weird Unicode for the image data. I've tried looking into this problem from scratch, but all the examples I've been finding have been used for static images already on the hard drive.
I've tried this for my code inside my JSP file and it works fine for JSON data posts. Can someone tell me if I'm on the right path at all for this?
try{
BufferedReader in = new BufferedReader(
new InputStreamReader(request.getInputStream()));
String inputLine;
StringBuffer resp = new StringBuffer();
while((inputLine = in.readLine()) != null){
resp.append(inputLine);
}
System.out.println("Images request line: \"" +resp.toString().substring(0, 200)+ "\"");
in.close();
}catch(Exception e){}

How to get whole data from Solr

I have to write some logic in Java which should retrieve all the index data from Solr.
As of now I am doing it like this
String confSolrUrl = "http://localhost/solr/master/select?q=*%3A*&wt=json&indent=true"
LOG.info(confSolrUrl);
url = new URL(confSolrUrl);
URLConnection conn = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
//save to this filename
String fileName = "/qwertyuiop.html";
File file = new File(fileName);
if (!file.exists())
{
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
while ((inputLine = br.readLine()) != null) {
bw.write(inputLine);
}
bw.close();
br.close();
System.out.println("Done");
In my file I will get the whole HTML file that I can parse and extract my JSON.
Is there any better way to do it?
Instead of get the resource from the url and parse it?
I just wrote an application to do this, take a look at github: https://github.com/freedev/solr-import-export-json
If you want read all data from a solr collection the first problem you're facing is the pagination, in this case we are talking of deep paging.
A direct http request like you did will return a relative short amount of documents. And you can even have millions or billions of documents in a solr collection.
So you should use the correct API, i.e. Solrj.
In my project I just did it.
I would also suggest this reading:
https://lucidworks.com/blog/2013/12/12/coming-soon-to-solr-efficient-cursor-based-iteration-of-large-result-sets/

Base64 image data is not getting in android

I am using HTTPURLConnection to connect to server and my response contains Base64 image data. When trying to read the response using getInputStream its not reading the complete response, breaks in between. My response contains list of objects in JSON format and each object contains BASE64 image data. Reading breaks while trying to read the first image data from the first object. Though its not showing any error it displays till half of the image data.How do i get the full response?? Here is my code
InputStream is = httpURLConnection.getInputStream();
byte[] b = new byte[1024];
StringBuffer buffer=new StringBuffer();
while ( is.read(b) != -1){
buffer.append(new String(b));
System.out.println("Read= "+is.read());
}
System.out.println(buffer);
Have you tried the example code from Google?
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
where readStream is your own method.
Reading from a BufferedInputStream is easier and faster.

Transmission of files through Socket or HTTP, between Android devices and desktops

I have custom socket client server data (file or text) transmission code. Now when I transfer binary files, some bytes convert onto out of range characters. So I send them in hex string. That works. But for another problem this is not the solution. This has a performance problems as well.
I took help from Java code To convert byte to Hexadecimal.
When I download images from the net, same thing happens. Some bytes change into something else. I have compared bytes by bytes.
Converting into String show ? instead of the symbol. I have tried readers and byte array input stream. I have tried all the examples on the net. What is the mistake I could be doing?
My Code to save bytes to file:
void saveFile(String strFileName){
try{
URL url = new URL(strImageRoot + strFileName);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
BufferedWriter bw = new BufferedWriter(new FileWriter(strImageDownloadPath + strFileName));
String line = null;
while ( (line = reader.readLine()) != null) {
bw.write(line);
}
}catch(FileNotFoundException fnfe){
System.out.println("FileNotFoundException occured!!!");
}catch(IOException ioe){
}catch(Exception e){
System.out.println("Exception occured : " + e);
}finally{
System.out.println("Image downloaded!!!");
}
}
i had a similar issue when i was building a Socket client server application. The bytes would be some weird characters and i tried all sorts of things to try and compare them. Then i came across a discussion where some1 pointed out to me that i should use a datainputstream, dataoutstream and let that do the conversion to and from bytes. that worked for me totally. i never touched the bytes at all.
use this code
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/image");
if(dir.exists()==false) {
dir.mkdirs();
}
URL url = new URL("http://4.bp.blogspot.com/-zqJs1fVcfeY/TiZM7e-pFqI/AAAAAAAABjo/aKTtTDTCgKU/s1600/Final-Fantasy-X-Night-Sky-881.jpg");
//URL url = new URL(DownloadUrl);
//you can write here any link
File file = new File(dir,"Final-Fantasy-X-Night-Sky-881.jpg");
long startTime = System.currentTimeMillis();
//Open a connection to that URL.
URLConnection ucon = url.openConnection();
//* Define InputStreams to read from the URLConnection.
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
//* Read bytes to the Buffer until there is nothing more to read(-1).
ByteArrayBuffer baf = new ByteArrayBuffer(6000);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
//Convert the Bytes read to a String.
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.flush();
fos.close();
You should take the help of this link: How to encode decode in base64 in Android.
You can send byte array obtained from a file as string by encoding into Base64. This reduces the amount of data transmitted as well.
At the receiving end just decode the string using Base64 and obtain byte array.
Then you can use #Deepak Swami's solution to save bytes in file.
I recently found out that PHP service APIs do not know about what is byte array. Any String can be byte stream at the same time, so the APIs expect Base64 string in the request parameter. Please see the posts:
String to byte array in php
Passing base64 encoded strings in URL
Hence Base64 has quite importance as also it allows you to also save byte arrays in preferences, and increases performance if you have to send file data across network using Serialization.
Happy Coding :-)

java code to download a file from server

using java code in windows i need to download several files from a directory placed in a server. those files in server are generated separately. so i'll not know the name of those files. is there any way to download it using JAVA and saving it in a specific folder.
i am using apache tomcat.
I read all other threads related to java file download. But none of them satisfy my requirement.
try {
// Get the directory and iterate them to get file by file...
File file = new File(fileName);
if (!file.exists()) {
context.addMessage(new ErrorMessage("msg.file.notdownloaded"));
context.setForwardName("failure");
} else {
response.setContentType("APPLICATION/DOWNLOAD");
response.setHeader("Content-Disposition", "attachment"+
"filename=" + file.getName());
stream = new FileInputStream(file);
response.setContentLength(stream.available());
OutputStream os = response.getOutputStream();
os.close();
response.flushBuffer();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Hope you got some idea...
Use java.net.URL and java.net.URLConnection classes.
Hi you can use this following code snippet to down the file directly :
URL oracle = new URL("http://www.example.com/file/download?");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
Kindly refer about openStream in this [URL] : http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html
You can use HttpURLConnection to download file over HTTP, HTTPS
It is only possible if server lists directory contents. if it does, your can make an HTTP request to:
http://server:port/folder
that would give you list of files.
Once you have that, you can download individual files by parsing output if this http request.
If it is server, then the process must be like using the FTP credentials you have to dosnload the files. This java file download example may help you.

Categories