CQ5 - How to get the page Image - java

I'm fairly new to CQ5, and I've got the following problem.
I'm trying to display a list with the images behind the childpages. I managed to get the list itself working, but there's something wrong with the images, the path to it isn't correct .
So far I've got this
<div class="img-list">
<img src="${list.img}" />
</div>
and
public class ImageList {
private String img = "";
private Page listItem;
String extension;
Resource r;
public ImageList(Page p ) {
this.listItem = p;
this.r = listItem.getContentResource("image");
}
public String getImg() {
if (r != null) {
//Image image = new Image(r);
img = r.getPath();
}
return img;
}
public void setImg (String i) {
this.img = i;
}
}
But this isn't working. Can anybody help me out?
Thanks in advance
Edit, got it working with the following solution:
public String getImg() {
String imagePath = "";
if (r != null) {
Image image = new Image(r);
imagePath = (String)listItem.getPath()+".img.png"+ image.getSuffix();
}
return imagePath;
}

If I understand correctly, you are trying to get a list of images from the child pages.
Why not try creating a Page object, which is mapped to your current page (essentially, a current page object) and then use the listChildren method to list out all of the child pages. Then you can use the page.getContentResorce("image") method, create an image object and then return the path for images associated with each child page..
Something like this:-
Iterator<Page> childPageIterator = Currentpage.listChildren(new PageFilter(request));
while(pageIterator.hasNext())
{
Page childPage = pageIterator.next();
Resource r = page.getContentResource("image");
if (r != null) {
Image image = new Image(r);
String imagePath = (String)contentpage.getPath()+".img.png"+ image.getSuffix();
}
}
You may need to tailor this as per your needs, but hopefully this should get you started

You are trying to get the path of the resource(image node) and provide it to the src attribute of the image tag, instead of the providing the actual path of the image.
One way of approaching this by changing the getImg() method as shown below
public String getImg() {
if (r != null) {
Node node = r.adaptTo(Node.class);
if(node.hasProperty("fileReference"){
img = node.getProperty("fileReference").getString();
}
}
return img;
}
Or you can use the com.day.cq.wcm.foundation.Image class to draw the image by passing the resource object, instead of using the img tag.

Related

Create file structure from strings

I am trying to create a BitBucket plugin to get the repository structure and print it out in a structured format. The plugin creates a button on the repo page and when clicked it connects with a servlet to produce an output, however I cannot get my formatting code to work.
E.g
Instead of:
Folder 1
File 1
File 2
I want it to indent children:
Folder 1
File 1
File 2
I currently have a JS file which controls the button and makes an ajax call to a Java file, and also passes the servlet URL including the parameters for the repo (Project, Repo).
In my Java file I have a doGet which gets the repo from the parameters and uses a custom contentTreeCallback() to get the files within the repo in order to print them out, using callback.getFiles(). Within this same Java file, I have defined a node class which creates a linked hash map which takes each file, splits it into components, and with a recursive loop appends children to nested lists in order to create the file structure. This should work, however my custom contentTreeCallback() gets a string rather than the file array it needs to return. I cannot figure out what changes I need to make to get this to work. I'm guessing I either adjust the callback to get the files or I move the node class functionality into the callback class. I would prefer the second option since this class already splits the string, it seems a bit redundant to do it twice.
The servlet java class:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// Get values from the URL
projectName= req.getParameter("project");
repoName = req.getParameter("repository");
repo = repositoryService.getBySlug(projectName, repoName);
// ByteArrayOutputStream out = new ByteArrayOutputStream();
MyContentTreeCallback callback = new MyContentTreeCallback();
PageRequestImpl pr = new PageRequestImpl(0, 1000);
// Get information from the defined location, store in ByteArrayOutputStream
contentService.streamDirectory(repo, "Master", "", true, callback, pr);
resp.setContentType("text/html");
resp.getWriter().print("<html><body><p>Repository: " + repo.getName() + "</p>");
Node root = new Node(null);
for(int i = 0; i < callback.getFiles().size(); i++) {
root.add(callback.getFiles().get(i));
}
root.writeTo(resp.getWriter());
resp.getWriter().print("</body></html>");
}
static final class Node {
final String name;
final Map<String, Node> children = new LinkedHashMap<>();
Node(String name) {
this.name = name;
}
void add(File file) {
Node n = this;
for(String component: file.getPath().getComponents())
n = n.children.computeIfAbsent(component, Node::new);
}
void writeTo(Appendable w) throws IOException {
if(name != null) w.append("<li><a href='/'>").append(name).append("</a></li>\n");
if(!children.isEmpty()) {
w.append("<ul>\n");
for(Node ch: children.values()) ch.writeTo(w);
w.append("</ul>\n");
}
}
}
And the custom callback class:
public class MyContentTreeCallback extends AbstractContentTreeCallback {
ArrayList<File> files = new ArrayList<File>();
ContentTreeSummary fileSummary;
public MyContentTreeCallback() {
}
#Override
public void onEnd(#Nonnull ContentTreeSummary summary) {
fileSummary = summary;
}
#Override
public void onStart(#Nonnull ContentTreeContext context) {
System.out.print("On start");
}
#Override
public boolean onTreeNode(#Nonnull ContentTreeNode node) {
String filePath = "";
if (node.getPath().getComponents().length>1) {
for(int i=0;i<node.getPath().getComponents().length;i++) {
filePath+=node.getPath().getComponents()[i]+"/";
//filePath=filePath.substring(0,filePath.length() - 1)
}
}
else {
filePath+=node.getPath().getName();
}
String lastChar = String.valueOf(filePath.charAt(filePath.length() - 1));
if(lastChar.equals("/")){ filePath=filePath.substring(0,filePath.length() -
1); }
files.add(filePath);
return true;
}
public ArrayList<File> getFiles(){
return files;
}
}
files.add(filePath); Is where the issue is in the callback class.
I'm sure it's simpler than I am making it out to be... Thanks for any help you can give

getDefaultToolkit() has a private access on toolkit

I have tried to set my Image icon but I get the error "getDefaultToolkit() has a private access on toolkit", can anybody help me?
#override
Public Image getIconImage() {
Image retValue = Toolkit.getDefaulttoolkit().getImage(
ClassLoader.getSystemResource("images/icon.png"));
return retValue;
}
Based on source here looks like you need:
#override
public Image getIconImage() {
Image retValue = Toolkit.getToolkit().getImage(
ClassLoader.getSystemResource("images/icon.png"));
return retValue;
}
Or as mentioned by #CarlosHeuberger, try java.awt.Toolkit.

display different 3D objects based on detected image's index in image database arcore

I have created an imgdb file consisting of images that I want to detect in arcore sceneform. Once I detect an image, I wish to display an augmented 3D object where the image was detected. Now, I wish to display a different 3D object depending on which image within the imgdb file was detected.
Something like this? But my app keeps crashing if I do this in the AugmentedImageNode.java file.
public class AugmentedImageNode extends AnchorNode {
private static final String TAG = "AugmentedImageNode";
public AugmentedImage image;
private static CompletableFuture<ModelRenderable> ulCorner;
public AugmentedImageNode(Context context) {
int imagenumber;
imagenumber = image.getIndex();
if (imagenumber == 0) {
if (ulCorner == null) {
ulCorner =
ModelRenderable.builder()
.setSource(context, Uri.parse("models/tinker.sfb"))
.build();
}
}
if (imagenumber == 1) {
if (ulCorner == null) {
ulCorner =
ModelRenderable.builder()
.setSource(context, Uri.parse("models/borderfence-small.sfb"))
.build();
}
}
}
Here are the logcat details:
enter image description here

JSF/primefaces display image out of code - Image Location?

I'm using JSF with primefaces and want to display an image from java code.
I already saw the tutorial on http://www.primefaces.org/showcase/ui/dynamicImage.jsf
But I'm not clear on how I can get the path to my image file correctly:
Code:
Bean:
#ManagedBean
public class ABean {
private StreamedContent bStatus;
public ABean() {
try {
Boolean connected = false;
if (connected == true) {
bStatus = new DefaultStreamedContent(new FileInputStream(new File("/images/greendot.png")), "image/jpeg");
} else {
bStatus = new DefaultStreamedContent(new FileInputStream(new File("/images/reddot.png")), "image/jpeg");
}
} catch(Exception e) {
e.printStackTrace();
}
}
public StreamedContent getBStatus() {
return bStatus;
}
public void setBStatus(StreamedContent bStatus) {
this.bStatus = bStatus;
}
}
xhtml:
<p:graphicImage value="#{ABean.bStatus}" />
returns:
java.io.FileNotFoundException: \images\reddot.png
I would appreciate best practices on where to store my image when displaying it form code and how to do it.
Since your images are in your web folder, you don't really need to use DefaultStreamedContent. I'd leave that only for images generated on the fly.
For your case, I'd just create a simple method that returns the image path (in your web folder) based on the boolean variable. Something like this:
public String getImagePath(){
return connected ? "/images/greendot.png" : "/images/reddot.png";
}
And on the graphicImage, you can just reference that:
<p:graphicImage value="#{yourBean.imagePath}"/>
Note that you might have to adjust the graphicImage tag if your web context is not root.
EDIT
You can actually make this even simpler:
<p:graphicImage value="#{yourBean.connected ? '/images/greendot.png' : '/images/reddot.png'}"/>
Just make sure to have a getter for the connected property.
Create your StreamedContent as follows:
bStatus = new DefaultStreamedContent(FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/images/greendot.png"), "image/jpeg");
When you are creating new File() this will be absolute path in your disk, not just in your application.

Need to parse image src from HTML page then display it

I'm currently trying to develop an app whereby it visits the following site (Http://lulpix.com) and parses the HTML and gets the img src from the following section
<div class="pic rounded-8" style="overflow:hidden;"><div style="margin:0 0 36px 0;overflow:hidden;border:none;height:474px;"><img src="**http://lulpix.com/images/2012/April/13/4f883cdde3591.jpg**" alt="All clogged up" title="All clogged up" width="319"/></div></div>
Its of course different every time the page is loaded so I cannot give a direct URL to an Asynchronous gallery of images which is what i intend to do, for instance
Load Page > Parse img src > download ASync to imageview > Reload lulpix.com > start again
Then place each of these in an image view from which the user can swipe left and right to browse.
So the TL;DR of this is, how can i parse the html to retrieve the URL and has anyone got any experiences with libarys for displaying images.
Thank you v much.
Here's an AsyncTask that connects to lulpix, fakes a referrer & user-agent (lulpix tries to block scraping with some pretty lame checks apparently). Starts like this in your Activity:
new ForTheLulz().execute();
The resulting Bitmap is downloaded in a pretty lame way (no caching or checks if the image is already DL:ed) & error handling is overall pretty non-existent - but the basic concept should be ok.
class ForTheLulz extends AsyncTask<Void, Void, Bitmap> {
#Override
protected Bitmap doInBackground(Void... args) {
Bitmap result = null;
try {
Document doc = Jsoup.connect("http://lulpix.com")
.referrer("http://www.google.com")
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.get();
//parse("http://lulpix.com");
if (doc != null) {
Elements elems = doc.getElementsByAttributeValue("class", "pic rounded-8");
if (elems != null && !elems.isEmpty()) {
Element elem = elems.first();
elems = elem.getElementsByTag("img");
if (elems != null && !elems.isEmpty()) {
elem = elems.first();
String src = elem.attr("src");
if (src != null) {
URL url = new URL(src);
// Just assuming that "src" isn't a relative URL is probably stupid.
InputStream is = url.openStream();
try {
result = BitmapFactory.decodeStream(is);
} finally {
is.close();
}
}
}
}
}
} catch (IOException e) {
// Error handling goes here
}
return result;
}
#Override
protected void onPostExecute(Bitmap result) {
ImageView lulz = (ImageView) findViewById(R.id.lulpix);
if (result != null) {
lulz.setImageBitmap(result);
} else {
//Your fallback drawable resource goes here
//lulz.setImageResource(R.drawable.nolulzwherehad);
}
}
}
I recently used JSoup to parse invalid HTML, it works well! Do something like...
Document doc = Jsoup.parse(str);
Element img = doc.body().select("div[class=pic rounded-8] img").first();
String src = img.attr("src");
Play with the "selector string" to get it right, but I think the above will work. It first selects the outer div based on the value of its class attribute, and then any descendent img element.
No need to use webview now check this sample project
https://github.com/meetmehdi/HTMLImageParser.git
In this sample project I am parsing html and image tag, than extracting the image from image URL. Image is downloaded and is displayed.

Categories

Resources