How to get image dimensions in Magnolia CMS - java

I have an absolute positioned image whose parent container I need to set a height on, but now I can't find a method in magnolia API that allows me to get the width or height of an asset/item.
Is there a way to get Image Dimensions (height, width) of an Asset/Item in Magnolia CMS using only the native API?
If not, how would you do it?

I would write it somehow like
import info.magnolia.dam.api.metadata.MagnoliaAssetMetadata;
// ...
if (asset.supports(MagnoliaAssetMetadata.class)) {
MagnoliaAssetMetadata metadata = asset.getMetadata(MagnoliaAssetMetadata.class);
long width = metadata.getWidth();
long height = metadata.getHeight();
// do whatever you need with the image dimensions
} else {
// handle non-image asset
}
See MagnoliaAssetMetadata javadoc and/or sources (and related classes) for more info.

I have done something like this, base on what you have suggested. I am using damTemplatingFunctions to get the asset using the JCR id.
Node node = nodes.nextNode();
String imageJcrId = node.getProperty("image").getValue().getString();
Asset asset = damTemplatingFunctions.getAsset(imageJcrId);
MagnoliaAssetMetadata metadata1 = asset.getMetadata(MagnoliaAssetMetadata.class);
System.out.println(metadata1.getHeight());
System.out.println(metadata1.getWidth());

Related

Icepdf annotation let page disappear

I'm developing an application that use Icepdf to show a pdf and draw something upon it.
I have a square annotation floating over the page but i have a nasty issue.
If i change page and come back to the page where the annotation is visible, if i move the annotation by dragging it the content of the page disappear becoming completely blank. This is the portion of code i use to show the moving annotation on top of the pdf.
Probably I'm missing something or doing it in wrong way.
controller.setAnnotationPanel(null);
controller.setDocumentToolMode(DocumentViewModelImpl.DISPLAY_TOOL_SELECTION); controller.getDocumentViewController().setViewCursor(DocumentViewController.CURSOR_SELECT);
Rectangle bbox = new Rectangle((int) (getPageWidth(getLastPage()) - SIGN_BOX_WIDTH - SIGN_BOX_MARGIN), SIGN_BOX_MARGIN, SIGN_BOX_WIDTH, SIGN_BOX_HEIGHT);
int index = getLastPage() - 1;
Document document = controller.getDocument();
DocumentViewModel documentViewModel=controller.getDocumentViewController().getDocumentViewModel();
PageTree pageTree = document.getPageTree();
Page page = pageTree.getPage(index);
// create and init the page's annotation components. [b]
java.util.List<AbstractPageViewComponent> pageComponents=controller.getDocumentViewController().getDocumentViewModel().getPageComponents();
AbstractPageViewComponent pageViewComponent = pageComponents.get(getLastPage() - 1);
tsq = (SquareAnnotation) AnnotationFactory.buildAnnotation(controller.getDocument().getPageTree().getLibrary(),Annotation.SUBTYPE_SQUARE,bbox);
BorderStyle bs = new BorderStyle();
bs.setBorderStyle(BorderStyle.BORDER_STYLE_SOLID);
bs.setStrokeWidth(2.0f);
tsq.setColor(Color.red);
tsq.setBorderStyle(bs);
tsq.setBBox(bbox);
tsq.setRectangle(bbox);
AffineTransform at = controller.getDocument().getPageTree().getPage(getLastPage() - 1).getPageTransform(controller.getDocumentViewController().getDocumentViewModel().getPageBoundary(), controller.getUserRotation(), controller.getUserZoom());
tsq.resetAppearanceStream(at);
SquareAnnotationComponent annotationComponent= (SquareAnnotationComponent) AnnotationComponentFactory.buildAnnotationComponent(tsq,controller.getDocumentViewController(),pageViewComponent,controller.getDocumentViewController().getDocumentViewModel());
annoCB.setCurrentAnnotation(annotationComponent);
controller.getDocument().getPageTree().getPage(getLastPage() - 1).addAnnotation(tsq);
Please assist to solve.
I had to work around on this, no real clue hot to solve.

Itext : set zoom level of external hyper link in pdf

I am using following code to set external hyperlink using itext library in Java.
Chunk chunk = new Chunk("Click to Open File");
PdfAction action = new PdfAction("externalfile.pdf");
action.put(PdfName.NEWWINDOW, PdfBoolean.PDFTRUE);
action.put(PdfName.ZOOM, PdfName.FIT);
chunk.setAction(action);
I want to set zoom level of external hyper link: when I click on hyper link file should be open and FIT page.
I tried using action.put(PdfName.ZOOM, PdfName.FIT); but it's not working.
Please don't ever create PDF object manually without consulting ISO-32000-1.
You want to create a GoToR action. Such an action is expressed as a PDF dictionary that can contain the following keys:
There is no key named Zoom in that table, hence your code is wrong.
You need the D key and as you want to link to a page and define a zoom factor, you need to define a destination:
In other words, the destination needs to be a PdfArray! PdfName.FIT isn't sufficient!
(All screen shots are taken from the copy of ISO-32000-1 that is provided by Adobe on its web site.)
Update:
If you want to add a link to a remote page, you can also follow the example on page 197-198 of iText in Action - Second Edition: see the LinkActions example that uses the gotoRemotePage() method.
Internally, this method looks like this:
public static PdfAction gotoRemotePage(String filename, String dest, boolean isName, boolean newWindow) {
PdfAction action = new PdfAction();
action.put(PdfName.F, new PdfString(filename));
action.put(PdfName.S, PdfName.GOTOR);
if (isName)
action.put(PdfName.D, new PdfName(dest));
else
action.put(PdfName.D, new PdfString(dest, PdfObject.TEXT_UNICODE));
if (newWindow)
action.put(PdfName.NEWWINDOW, PdfBoolean.PDFTRUE);
return action;
}
Note that this assumes that you have a named destination in the target file.
I think that you'd rather want to use the constructor that takes a page number:
public PdfAction(String filename, int page) {
put(PdfName.S, PdfName.GOTOR);
put(PdfName.F, new PdfString(filename));
put(PdfName.D, new PdfLiteral("[" + (page - 1) + " /FitH 10000]"));
}
Of course, this doesn't use PdfName.FIT. If you really want to define the destination yourself, you need a line that looks like this:
put(PdfName.D, new PdfLiteral("[" + (page - 1) + " /Fit]"));

Good practice loading assets LibGDX HTML (GWT)

I'm creating a game that will mainly run on browser thanks to GWT HTML5 deployment. I have quite a few MB of assets between images and sounds. Obviously I don't need them all at all times. I'd like to load them depending on the screen that's coming next and other parameters. That is specially critical because my main deployment will be on web (can't load all 50MB when starting just in case they will be used).
I don't really know how asset loading works on LibGDX on HTML5 really. I'd like to use the AssetManager or something similar to load my TextureAtlases and Sounds but I think HTML5 deployment just loads everything in the beginning regardless if I later use the AssetManager in the core project.
What would be a correct asset loading pipeline with libGDX and GWT. It would be awesome to load all from the core project because that way would be multiplatform for the future but it is not critical now so the important part is to load assets wisely on the web.
Thanks in advance.
My recommended way of managing assets:
// load texture atlas
final String spriteSheet = "images/spritesheet.pack";
assetManager.load(spriteSheet, TextureAtlas.class);
// blocks until all assets are loaded
assetManager.finishedLoading();
// all assets are loaded, we can now create our TextureAtlas object
TextureAtlas atlas = assetManager.get(spriteSheet);
// (optional) enable texture filtering for pixel smoothing
for (Texture t: atlas.getTextures())
t.setFilter(TextureFilter.Linear, TextureFilter.Linear);
Now to load a sprite you do:
// Create AtlasRegion instance according the given <atlasRegionName>
final String atlasRegionName = "regionName";
AtlasRegion atlasRegion = atlas.findRegion(atlasRegionName);
// adjust your sprite position and dimensions here
final float xPos = 0;
final float yPos = 0;
final float w = asset.getWidth();
final float h = asset.getHeight();
// create sprite from given <atlasRegion>, with given dimensions <w> and <h>
// on the position of the given coordinates <xPos> and <yPos>
Sprite spr = new Sprite(atlasRegion, w, h, xPos, yPos);

How to load a Google maps static map using Picasso?

In my Android app I use Picasso to load images. This normally works perfectly well.
Today I tried loading a static image from the google maps api, but this doesn't seem to work. When I open the example link as provided on their info page, I get to see the static map image perfectly well. When I load it in my Android app using the line below, I get nothing at all.
Picasso.with(getContext()).load("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=370x250&maptype=roadmap%20&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318%20&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false").into(mapView);
I also tried to download the image and uploading it to my personal webspace, from which it loads perfectly well, but somehow, it doesn't seem to load directly from the direct google API url.
Does anybody know why this is so, and how I can solve it?
The only programmatic point-of-failure that comes to mind is in parsing the URI. Looking at the current Picasso code (https://github.com/square/picasso/blob/master/picasso/src/main/java/com/squareup/picasso/Picasso.java) I see the following:
public RequestCreator load(String path) {
if (path == null) {
return new RequestCreator(this, null, 0);
}
if (path.trim().length() == 0) {
throw new IllegalArgumentException("Path must not be empty.");
}
return load(Uri.parse(path));
}
So I'd first debug
Uri.parse("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=370x250&maptype=roadmap%20&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318%20&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false")
and see what that Object looks like. Does it drop or confuse any of your parameters?
If that doesn't lead you anwhere, try downloading the file manually using a HttpClient [or similar]. Then at least you can fully debug the request/response.
Also, I know Google maps has some limits -- are you sure you haven't reached them?
replace http with https
replace | with %7C
add api key
The .loadMap() function has many declared variables. This is the heart of the whole process.
So what is required for the static maps API to give us an image is that we make an http request with a given url, for which an image response (URL) is received. Let us run through the meaning and utility of these variables. Yes, all of them have a completely different meaning!
The mapUrlInitial variable is always the same while making an API call. It has a query of center ( ?center ) which specifies that we want the location to be centered in the map.
The mapUrlProperties variable contains a string where you control the actual zooming of the image response you will get, the size ofthe image and the color of the marker which will point out our place.
The mapUrlMapType variable is a string where you can actually determine the marker size you want and the type of the map. We are using a roadtype map in the app.
Finally latLong is a string which concatenates the latitude and the longitude of the place we want to pinpoint!
We then concatenate all of these strings to form a feasible Url. The Url is then loaded as we have seen above, in the Picasso code. One thing we can notice is that an event object is always required for all of this to happen, because we are able to fetch the position details using the event object! Final Code:-
fun loadMap(event: Event): String{
//location handling
val mapUrlInitial = “https://maps.googleapis.com/maps/api/staticmap?center=”
val mapUrlProperties = “&zoom=12&size=1200×390&markers=color:red%7C”
val mapUrlMapType = “&markers=size:mid&maptype=roadmap”
val latLong: String = “” +event.latitude + “,” + event.longitude
return mapUrlInitial + latLong + mapUrlProperties + latLong + mapUrlMapType
}
//load image
Picasso.get()
.load(loadMap(event))
.placeholder(R.drawable.ic_map_black_24dp)
.into(rootView.image_map)

iText error while trying to set an image field

I am using iText 5.3.4 and trying to set an image field, the below code is what Bruno suggested that I use however I am getting an error of "The type of the expression must be an array type but it resolved to List".
I see no documentation on how to write the code the way that the api is asking for.
Does anyone have an idea on how this should be written????
Or how to send an image to an image field?
Rectangle rect = form.getFieldPositions(fieldName)[0].position;
int page = form.getFieldPositions(fieldName)[0].page;
image1.scaleAbsolute(rect.getWidth(), rect.getHeight());
img.setAbsolutePosition(rect.getLeft(), rect.getBottom());
stamper.getOverContent(page).addImage(img);
The return from getFieldPositions is of type List<AcroFields.FieldPosition>, so the complaint is valid. You should use .get(0) rather than [0] to reference the first item in the collection.
A simple refactoring might be:
List<AcroFields.FieldPosition> positions = form.getFieldPositions(fieldName);
Rectangle rect = positions.get(0).position;
int page = positions.get(0).page;
image1.scaleAbsolute(rect.getWidth(), rect.getHeight());
img.setAbsolutePosition(rect.getLeft(), rect.getBottom());
stamper.getOverContent(page).addImage(img);

Categories