how to use Images without path in handlebars - java

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}}"/>

Related

How can I use custom font in Jeuclid (Java)?

this is the code where I am converting MathMl to png
public static void main(String[] args) throws IOException, FontFormatException {
Converter converter = Converter.getInstance();
String math="<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mfenced open=\"[\" close=\"]\"><mtable><mtr><mtd><mn>3</mn></mtd><mtd><mn>2</mn></mtd></mtr><mtr><mtd><mn>6</mn></mtd><mtd><mn>7</mn></mtd></mtr><mtr><mtd><mn>6</mn></mtd><mtd><mn>4</mn></mtd></mtr></mtable></mfenced><mo>=</mo><msubsup><mo>∫</mo><mn>5</mn><mn>4</mn></msubsup></math>";
File inputFile = new File("D:\\mathml.xml");
File outputFile = new File("D:\\image.jpg");
//params to mention the size of image
MutableLayoutContext params = new LayoutContextImpl(
LayoutContextImpl.getDefaultLayoutContext());
params.setParameter(Parameter.MATHSIZE, 50f);
Document doc = StringToDocumentToString.convertStringToDocument(math);
// Parameter parameter= new Pa
converter.convert(doc, outputFile , "image/jpeg", params);
}
I want to use Tahoma.ttf when I make png from MathMl but I can not find any resource how to do that. Please can anyone help me?

How to display uploaded image via CSS

i want to upload an image via primefaces:fileUpload and then display it on a div for example with css.
I can already save the image on the server:
public void upload() throws IOException, URISyntaxException {
if (logo != null) {
File fileImage = new File(System.getProperty("jboss.server.data.dir"), "uploads.png");
BufferedImage img = ImageIO.read(new ByteArrayInputStream(logo.getContents()));
if (fileImage.exists()) {
fileImage.delete();
}
ImageIO.write(img, "png", fileImage);
}
}
And then i tried to get the web path to the file but that didn't worked:
public String getImagePath(){
File fileImage = new File(System.getProperty("jboss.server.data.dir"), "uploads.png");
Set<String> set = FacesContext.getCurrentInstance().getExternalContext().getResourcePaths(fileImage.getAbsolutePath());
return set.iterator().next();
}
I need something like this:
/ewarehouse/javax.faces.resource/dynamiccontent.properties.xhtml?ln=primefaces&v=6.2&v=6.2&pfdrid=f52e395e4f38c09a1990e8f9d0c5806d&pfdrt=sc&pfdrid_c=true
Can someone help me or has a other way to do this ?
It worked for me to create a servlet and refered to the file position.
background-image: url('#{'/'}ewarehouse#{'/'}images//dynamic#{'/'}?file=uploads.png')
In css it look a bit weird but this way it worked Thanks for the answer to #JasperdeVries and #Kukeltje

Decoding QR code in photo using Zxing

I want to decode some photos with QR code.
I found this method:
public static String readQRCode(String filePath, String charset, Map hintMap) throws FileNotFoundException, IOException, NotFoundException {
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
new BufferedImageLuminanceSource(
ImageIO.read(new FileInputStream(filePath)))));
Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap, hintMap);
return qrCodeResult.getText();
}
It's working on pictures like this.
Unfortunately it doesn't work on all images, i.e: this. As you see it has poor quality.
Error: com.google.zxing.NotFoundException
Any ideas, what can I do?

How to get images from a folder in the server using Jersey WS?

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 ?

SEVERE: Error in streaming dynamic resource.(apache)

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 )

Categories

Resources