I have an several image in database saved as String and i want to loop in them and view them dynamically using primefaces.
the output is: sometimes show one image or two or nothing And I used all scopes (session ,view ,request) the result is the same.
here is the code, i used to convert string to streamed Content :
private StreamedContent getImageFromString(String imageData) throws IOException {
byte[] imageByte = null;
BufferedImage imageBuffer = null;
imageByte = byteToString(imageData);
ByteArrayInputStream in = new ByteArrayInputStream(imageByte);
imageBuffer = ImageIO.read(in);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(imageBuffer, "png", os);
return new DefaultStreamedContent(new ByteArrayInputStream(os.toByteArray()), "image/png");
}
public byte[] byteToString(String imageStr) {
return Base64.decodeBase64(imageStr);
}
and the jsf design is :
<ui:repeat value="#{recent.recentlist}" var="recent" >
<h:outputText value="#{recent.Id}"/>
<br/>
<p:graphicImage value="#{recent.graphicImage}">
<f:param name="image_id" value="#{recent.Id}"/>
</p:graphicImage>
<br/><br/>
<p:separator/>
</ui:repeat>
the result all the time is ( SEVERE: Error in streaming dynamic resource )
Related
I want to deliver image list into Handlebars view.
ArrayList<ImageIcon> images = new ArrayList<>();
for(Photos p : photos){
ByteArrayInputStream bis = new ByteArrayInputStream(p.getImage());
BufferedImage bim = ImageIO.read(bis);
images.add(new ImageIcon(bim));
}
model.addAttribute("photos", images);
I'm sure that there are ImageIcon objects in this arrayList by debugging.
Then, how can I use this array in handlebars like this.
{{#each photos as |photo|}}
<img src={{photo}}>
{{/each}}
I want to use this images without file path.
#GetMapping("/displayImage")
public void displayImage(#RequestParam("email")String email, HttpServletResponse response) throws IOException {
List<Photos> list = photoService.showImages(email);
byte[] binaryImage = list.get(0).getImage();
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
response.getOutputStream().write(binaryImage);
response.getOutputStream().close();
}
<img src="/displayImage/?email={{userInfo.email}}"/>
I am uploading images to Cloud Storage using the Java Client Library Images are uploaded to Bucket but when I am trying to access them, a Black screen is displaying in browser. So, I dug into this to check the type of the Image after it is uploaded into Cloud Storage.
I uploaded the image I downloaded from the cloud storage to
Check File Type .com and it is showing file type as data and MIME/TYPE as application/octet-stream instead of image
So , I uploaded the original image of the same from my PC and it is perfectly showing the image type as image/jpeg
Here is the code I have written using the Java client library.
HTML Form to handle the upload
<form action="/through" method="post" enctype="multipart/form-data">
<h3>Uploading File through App Engine instances to cloud storage</h3>
<label>Enter Your Team Name</label><br>
<input type="text" name="TeamName" ><br><br>
<label>Upload Team Logo</label><br>
<input type="file" name="teamLogo" required="required"><br><br>
<input type="submit" value="Upload Team Logo">
</form>
Java code to Upload the Image
InputStream input = request.getInputStream();
ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
try {
int read = input.read();
while(read != -1) {
byteArrayStream.write(read);
read = input.read();
}
catch (IOException e){
//Handle Exception
}
byte[] fileBytes = byteArrayStream.toByteArray();
Storage storage = null;
try {
FileInputStream credentialsStream = new FileInputStream("JSONFile");
Credentials credentials = GoogleCredentials.fromStream(credentialsStream);
storage = StorageOptions.newBuilder().setCredentials(credentials).setProjectId("myProjectID").build().getService();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BlobId blobId = BlobId.of(BUCKET_NAME, USER_NAME+"TeamLogo.jpg");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("image/jpeg").build();
Blob blob = storage.create(blobInfo, fileBytes);
Why Cloud Storage is not able to detect the type of image properly? It is having adverse effects on other parts of my application where I want to display the same images.
UPDATE
In Console for the same object, Content-Type is showing as image/jpeg
Try this code:
package com.example.storage;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import java.io.File;
import java.nio.file.Files;
public class QuickstartSample {
public static void main(String... args) throws Exception {
File fi = new File("source.jpg");
Storage storage = StorageOptions.getDefaultInstance().getService();
BlobId blobId = BlobId.of("your-bucket", "imagen.jpg");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("image/jpeg").build();
Blob blob = storage.create(blobInfo, Files.readAllBytes(fi.toPath()));
System.out.println(blob.getContentType());
}
}
I got the following result on CheckFileType:
Instead of uploading a file to your local instance, and then moving it to the Cloud Storage, you can instruct your client app to directly upload the file to the Cloud Storage using resumable upload.
If you do need to get file to your local instance first (e.g. for some processing before uploading it), you can use:
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = inStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
I have a pdf in C:/Reports/report.pdf and I need to download it using primefaces. As I have read I need to first get the InputStream of the file and use DefaultStreamedContent to get the StreamedContent but everything I tried failed.
Help me please it is supposed to be easy and have had lots of problems with this.
The info here uses the /resources/ web directory. I need to do that with the absolute path of the file.
I resolve it doing this:
<p:commandButton value="Download" ajax="false" actionListener="#{downloadBean.prepareDownload()}">
<p:fileDownload value="#{downloadBean.download}" />
</p:commandButton>
And:
#ManagedBean
public class DownloadBean {
/**
* Creates a new instance of DownloadBean
*/
private DefaultStreamedContent download;
public void setDownload(DefaultStreamedContent download) {
this.download = download;
}
public DefaultStreamedContent getDownload() throws Exception {
System.out.println("The file: " + download.getName());
return download;
}
public void prepareDownload() throws Exception {
File file = new File("C://ImagenesAlmacen/Reporte/report.pdf");
InputStream input = new FileInputStream(file);
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
setDownload(new DefaultStreamedContent(input, externalContext.getMimeType(file.getName()), file.getName()));
}
}
I am learning the Jersey web services, now I understood how GET and POST work :
#GET
#Produces("text/html")
public String getHandler() {
return "<h1>Get some REST!<h1>";
}
#POST
#Consumes("application/x-www-form-urlencoded")
#Produces("text/plain")
public String postHandler(String content) {
return content;
}
in Jersey Documentation for featching images it said :
#GET
#Path("/images/{image}")
#Produces("image/*")
public Response getImage(#PathParam("image") String image) {
if (!isSafeToOpenFile(image)) {
throw new IllegalArgumentException("Cannot open the image file.");
}
File f = new File(image);
if (!f.exists()) {
throw new WebApplicationException(404);
}
String mt = new MimetypesFileTypeMap().getContentType(f);
return Response.ok(f, mt).build();
}
I would appreciated if you can show me an example using the above code to fetch images from a folder in the server and post them in a html.
Thanks lot.
Here is a full example of a live gallery, based on REST services.
REST services (Jersey)
This service gives the content (filenames) of the image server directory (here C:\Temp\hotfolder).
// array of supported extensions
static final String[] EXTENSIONS = new String[] { "jpg", "jpeg", "gif", "png", "bmp" };
// filter to identify images based on their extensions
static final FilenameFilter IMAGE_FILTER = new FilenameFilter() {
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
#GET
#Path("folderImages")
#Produces("text/json")
public Response getFolderImages(#QueryParam("lastknown") String lastknown)
{
//Gets the contents of the folder (reverse order : more recent first)
//see http://stackoverflow.com/questions/11300847/load-and-display-all-the-images-from-a-folder
File dir = new File("C:\\Temp\\hotfolder");
File [] files = dir.listFiles(IMAGE_FILTER);
Arrays.sort( files, new Comparator<File>() {
public int compare(File f1, File f2) {
if (f1.lastModified() > f2.lastModified()) {
return -1;
} else if (f1.lastModified() < f2.lastModified()) {
return +1;
} else {
return 0;
}
}
});
//Fills a list (from the more recent one, until the last known file)
ArrayList<String> newfiles = new ArrayList<String>();
for (File f : files)
{
if (lastknown!=null && f.getName().equals(lastknown))
break;
newfiles.add(f.getName());
}
//Answers the list as a JSON array (using google-gson, but could be done manually here)
return Response.status(Status.OK).entity(new Gson().toJson(newfiles)).type("text/json").build();
}
Also this is the image service, needed for rendering each image individually.
#GET
#Path("/images/{image}")
#Produces("image/*")
public Response getImage(#PathParam("image") String image) {
File f = new File("C:\\Temp\\hotfolder\\" + image);
if (!f.exists()) {
throw new WebApplicationException(404);
}
String mt = new MimetypesFileTypeMap().getContentType(f);
return Response.ok(f, mt).build();
}
gallery.html
Html, with a little help of JQuery. This HTML polls every 5 seconds, asking for service if there is new files (more recent) than the last file known. Et voilĂ !
You can notice we are using the jquery .prepend method to insert images dynamically at the beginning of the gallery div.
<html>
<head>
<title>Folder demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<h1>Live gallery</h1>
<div id="gallery1" style="border:1px solid black;padding:10px;"></div>
<div id="info1"></div>
<script>
var counter = 0;
var lastknown = "";
function doPoll(){
$.get('rest/folderImages?lastknown='+lastknown, function(data) {
counter++;
$("#info1").html("<pre>Counter: " + counter + "<br>New files: " + data + "</pre>");
for (var i=data.length-1; i>=0; i--) {
$("#gallery1").prepend("<img src=\"rest/images/" + data[i] + "\" style=\"width:200px;height:200px\" />");
lastknown = data[i];
}
setTimeout(doPoll,5000);
});
}
$(document).ready( doPoll );
</script>
</body>
</html>
The Jersey example from documentation is clear enough to me. However, here is a simplified example without parameters (do simple to begin...)
#GET
#Path("/images/pet")
#Produces("image/*")
public Response getImage() {
File f = new File("C:\\\\Temp\\dog.jpg");
if (!f.exists()) {
throw new WebApplicationException(404);
}
String mt = new MimetypesFileTypeMap().getContentType(f);
return Response.ok(f, mt).build();
}
As my Jersey is configured as /rest/* path in the web.xml of the yourapp application, the image is accessible at the following address:
http://serverip:port/yourapp/rest/images/pet
You can try it directly this URL in the browser navigation bar (it is a REST image service, served as if it was a static image), or if you want it in a html page, you can use classic HTML:
<html>
<body>
<h1>Woof!</h1>
<img src="http://localhost:8080/myapp/rest/images/pet" />
</body>
</html>
Hope it helps.
EDIT
Okay that was too obvious. So you need to implement a method or service that gives the content of a directory with image file names in the given order you need (as a java List).
Using this List, you can build a html like this within a loop:
<html>
<body>
<h1>Several images</h1>
<img src="/yourapp/rest/images/last.jpg" /><br/>
<img src="/yourapp/rest/images/third.jpg" /><br/>
<img src="/yourapp/rest/images/second.jpg" /><br/>
<img src="/yourapp/rest/images/first.jpg" /><br/>
</body>
</html>
This is the result HTML you must output (in JSP or whatever you use). The REST service getImage() will be called automatically by the browser, once for each image.
Am I clear ?
I am submitting a JSP form with a string and on submit I am calling a Struts 2 action. In that action I am creating a QRCode image using QRGen library as below
File QRImg=QRCode.from("submitted String").to(ImageType.PNG).withSize(100, 100).file();
my JSP form:
<form action="createQR">
Enter Your Name<input type="text" name="userName"/><br/>
<input type="submit" value="Create QRCode"/>
</form>
My action Mapping struts.xml:
<action name="createQR" class="CreateQRAction">
<result name="success">displayQR.jsp</result>
</action>
My Action class:
import java.io.File;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
import com.opensymphony.xwork2.ActionSupport;
public class CreateQRAction extends ActionSupport{
private File QRImg;
Private String userName;
public String execute() {
QRImg=QRCode.from(userName).to(ImageType.PNG).withSize(100, 100).file();
return SUCCESS;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public File getQRImg() {
return QRImg;
}
public void setQRImg(File QRImg) {
this.QRImg = QRImg;
}
}
Now if result is success that I want to display this image on my JSP.
<s:property value="QRImg"/>
It seems you need the action the <s:url from that you could substitute in the <img tag as href attribute to retrieve the image similar to use static images like in the /images folder.
Let's call it ImageAction. This is a simple action that writes to the response out. To use it you need to put the file with image into the session. Because images are retrieved by the separate threads. In the execute method write
#Action(value = "image", interceptorRefs = #InterceptorRef("basicStack"))
public class ImageAction extends ActionSupport {
public String execute() {
Get the file from the session
File file = session.get("file");
then you need to read file
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[fis.available()];
fis.read(data);
fis.close();
then write to the response out
response.setContentType("image/png");
BufferedImage bi;
OutputStream os = response.getOutputStream();
bi = ImageIO.read(new ByteArrayInputStream(data));
ImageIO.write(bi, "PNG", os);
os.flush();
and return NONE result because this action only writes to the response
return NONE;
}
done
then in the JSP forwarded from your action just use <img src="<s:url action="image"/>" style="width:100%;"/>. If you need to add path then use namespace annotation on the action and attribute in the url.
I feel you are familiar with the session concept in the Struts2, i.e. how to inject the session into your action and map objects in it. Map the file object in your action before return the result.
Good luck.
you need to use the 'org.apache.struts2.dispatcher.StreamResult' in struts2. Basically in your action read the image and populate an InputStream. also setup other variables you require to correctly configure the 'stream' result. Use these in action mapping to property configure the result which would be of type 'stream'