Resize an image resource in CQ5 - thumbnails

I am trying to resize a given JCR image resource and store it as a new rendition. The use case is to generate thumbnails in "any" scale.
I wanted to use the com.day.cq.dam.core.process.CreateThumbnailProcess, but this it is not available in the project, i am working on.

I found a quite low level approach, to resize an image identified by jcrPathToImage to int targetWidth and int targetHeight.
Resize Image
Resource resource = getResourceResolver().getResource(jcrPathToImage);
Asset asset = resource.adaptTo(Asset.class);
Layer layer = new Layer(asset.getOriginal().getStream())
layer.resize(targetWidth, targetHeight);
Create new rendition in JCR
Extract mime type of the original image
Image image = new Image(resource);
String mimeType = image.getMimeType();
Store the resized Image using its asset representation.
ByteArrayOutputStream bout = null;
ByteArrayInputStream bin = null;
try {
bout = new ByteArrayOutputStream(2048);
layer.write(mimeType, 1, bout);
bin = new ByteArrayInputStream(bout.toByteArray());
asset.addRendition(resizedImgName, bin, mimeType);
} finally {
// close streams ...
}

you can configure the DAM Update Asset workflow to give the renditions you want to get created
http://localhost:4502/etc/workflow/models/dam/update_asset.html
in this workflow model select the thumbnail creation step and in the process tab of that step you can add your custom thumbnail values
[140:100],[48:48],[319:319],[90,90]

Related

itext 7 c# how to clip an existing pdf

let's say I have a bunch of pdf files that I want to migrate into a new pdf. BUT the new pdf file is a table-structured file. And the content of the pdf files should fit in the first cell of a two-column-table.
I am not sure if the approach of working with tables is correct. I am open to any other solutions. All I want is at the end some custom text at the top, followed by pdf content and a checkbox on the right side. (One per pdf content)
What I have so far:
`
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc, PageSize.A4);
doc.SetMargins(0f, 0f, 18f, 18f);
PdfReader reader = new PdfReader(src);
PdfDocument srcDoc = new PdfDocument(reader);
Table table = new Table(new float[] { 2f, 1f });
PdfFormXObject imagePage = srcDoc.GetFirstPage().CopyAsFormXObject(pdfDoc);
var image = new Image(imagePage);
Cell cell = new Cell().Add(image);
cell.SetHorizontalAlignment(HorizontalAlignment.LEFT);
cell.SetVerticalAlignment(VerticalAlignment.TOP);
table.AddCell(cell);
Table checkTable = new Table(2);
Cell cellCheck1 = new Cell();
cellCheck1.SetNextRenderer(new CheckboxCellRenderer(cellCheck1, "cb1", 0));
cellCheck1.SetHeight(50);
checkTable.AddCell(cellCheck1);
Cell cellCheck2 = new Cell();
cellCheck2.SetNextRenderer(new CheckboxCellRenderer(cellCheck2, "cb2", 1));
cellCheck2.SetHeight(50);
checkTable.AddCell(cellCheck2);
table.AddCell(checkTable);
doc.Add(table);
doc.Close();`
My Problem here is that the pdf content has still its margin. Which completely spoils the design. It is so frustrating, I appreciate any help.
You say
My Problem here is that the pdf content has still its margin. Which completely spoils the design.
PDFs (usually) don't know anything about margins. Thus, you have to detect the margins of the page to import first. You can do this by parsing the page content into an event listener that keeps track of the bounding box of drawing instructions, like the TextMarginFinder. Then you can reduce the source page to those dimensions. This can be done by means of the following method:
PdfPage restrictToText(PdfPage page)
{
TextMarginFinder finder = new TextMarginFinder();
new PdfCanvasProcessor(finder).ProcessPageContent(page);
Rectangle textRect = finder.GetTextRectangle();
page.SetMediaBox(textRect);
page.SetCropBox(textRect);
return page;
}
You apply this method in your code right before you copy the page as form XObject, i.e. you replace
PdfFormXObject imagePage = srcDoc.GetFirstPage().CopyAsFormXObject(pdfDoc);
by
PdfFormXObject imagePage = restrictToText(srcDoc.GetFirstPage()).CopyAsFormXObject(pdfDoc);
This causes the Image this XObject will be embedded in to have the correct size. Unfortunately it will be somewhat mispositioned because the restricted page still has the same coordinate system as the original one, merely its crop box defines a smaller section than before. To fix this, one has to apply an offset, one has to subtract the coordinates of the lower left corner of the page crop box which has become the XObject bounding box. Thus, add after instantiating the Image the following code:
Rectangle bbox = imagePage.GetBBox().ToRectangle();
image.SetProperty(Property.LEFT, -bbox.GetLeft());
image.SetProperty(Property.BOTTOM, -bbox.GetBottom());
image.SetProperty(Property.POSITION, LayoutPosition.RELATIVE);
Now the restricted page is properly positioned in your table cell.
Beware: The TextMarginFinder (as its name indicates) determines the margins by text alone. Thus, if the page contains other contents, too, e.g. decorations like a logo, this logo is ignored and might eventually be cut out. If you want such decorations, too, in your overviews, you have to use a different margin finder class.

IText PDFImage seems to shrink or disappear during new pages after upgrade from 2.1.7 to 5.5.5 (Java .jars)

I seem to have an issue after upgrading iText from 2.1.7 where the PDF seems to be missing or the image has shrunk between pages.
I'm wondering if this is a known issue or if there is something that I need to set in order to fix it.
Some context:
no real calculations have been changed when switching libraries.
the general structure is that we have a Document which has a pdfTable which holds a bunch of pdfImages.
changing between landscape and portrait produces different results.
the images are scaled down so that it will fit the page.
Edit: Sorry, my application was pretty big and does a bunch of work. I had to make a simple mock version before posting the problem
Sample Code (So the numbers are just examples that I used. I basically added a 800*600 Image 5 times using landscape position. I end up seeing only 3 pages when I am expecting 5.)
Note: Using portrait page size shows all 5 but it seems that the sizes vary for some reason.
ByteArrayOutputStream baos = createTemporaryOutputStream();
Document doc = newDocument();
PdfWriter writer = newWriter(doc, baos);
writer.setViewerPreferences(PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage);
//create page rectangle landscape
Rectangle page = new Rectangle(PageSize.A4.rotate());
doc.setPageSize(page);
doc.setMargins((float)36.0, (float)36.0, (float)36.0, (float)36.0);
doc.open();
//create element pdf table.
PdfPTable table = new PdfPTable(new float[]{(float) 770.0});
table.setWidthPercentage(100);
table.setSplitRows(true);
table.setSplitLate(false);
table.setHeaderRows(0);
// in my case I used 5 800*600 images (same picture)
//then I loop through them and create pdfcell
//and then add it to table which then gets added to the document
List<Image> hi = (List<Image>) model.get("images");
for (Image image : hi) {
com.itextpdf.text.Image pdfImage = com.itextpdf.text.Image.getInstance(image.getBytes());
pdfImage.scalePercent((float) (0.8642384 * 100));
PdfPCell cell = new PdfPCell(pdfImage, false);
table.addCell(cell);
}
doc.add(table);
doc.close();

cn1 - get file path to image for share()

I'm trying to use the share() method, including an image, but I'm having trouble supplying the proper path to the image. Where should I put the image file, and what is the path (putting in the default package and trying "jar:///myimage.png" didn't work), and why is this not documented clearly?
image can be stored in storage which is following path for window
C:\Users\userName.cn1
and the image can be read by using following codes
InputStream is = Storage.getInstance().createInputStream("tizbn.JPG");
EncodedImage i = EncodedImage.create(is, is.available());
Loading image from default folder
Image i =EncodedImage.create("/tizbn.png");
Loading image From Theme
EncodedImage current = (EncodedImage) fetchResourceFile().getImage("tizbn.png");
The share API works with https://www.codenameone.com/javadoc/com/codename1/io/FileSystemStorage.html[FileSystemStorage] and not with https://www.codenameone.com/javadoc/com/codename1/io/Storage.html[Storage].
You need to save the file into a file system path which is always an absolute path, we recommend using the app home to store files. There is a sample in the developer guide section on the ShareButton covering this:
Form hi = new Form("ShareButton");
ShareButton sb = new ShareButton();
sb.setText("Share Screenshot");
hi.add(sb);
Image screenshot = Image.createImage(hi.getWidth(), hi.getHeight());
hi.revalidate();
hi.setVisible(true);
hi.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
Log.e(err);
}
sb.setImageToShare(imageFile, "image/png");

Listview display wrong image at wrong place when loading thumbnail image from web

I am using List view for displaying android files i.e. showing Folder and files from server.
When i start my activity, i can see the list on the screen, just as i want it.
and I am getting data from server.
I want to show structure like
when there is image file need to show image thumbnail (I have thumbnail URL which is getting from server by default imageloader displaying default image icon until thumbnail is not available).
when there is other file type like audio,video..... or file need to show that icon.
and when I am showing list it shows proper icon for related files.
But the moment i try to start scrolling the and in background my thumbnail is loading from server and when from server I am getting image from server and showing that bitmap thumbnail it will displaying thumbnail bitmap in other file type like folder or music file icon due to view reusing of listview.
this misplace is happen when getting image from server.
any one can please suggest me to how to overcome this problem.
below is my getview() method of my listview.
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder viewHolder = new ViewHolder();
if(convertView == null){
convertView = _inflate.inflate(R.layout.layout_list, null);
viewHolder.text = (TextView) convertView.findViewById(R.id.title);
viewHolder.owner = (TextView) convertView.findViewById(R.id.owner);
viewHolder.image = (ImageView) convertView.findViewById(R.id.thumb);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> item = (HashMap<String, String>) getItem(position);
viewHolder.text.setText( item.get("poiName").toString() );
viewHolder.owner.setText( item.get("owner").toString() );
ImageView imageView = viewHolder.image;
imageView.setTag(item.get("thumbs"));
//Is type of file is picture then display thumbnail by using imagloader class
if (genericDAO.sub_content_type.equalsIgnoreCase(Constants.TYPE_PICTURE))
{
String url = getTumbnalURL();
viewHolder.image.setTag(genericDAO.id);
viewHolder.image.setScaleType(ScaleType.CENTER_CROP);
mImageLoader.DisplayImage(id, url, mActivity,viewHolder.image);
}
else
{
//Display related file icon
viewHolder.image.setImageResource(FileUtil.getImageRelatedToFileType(mcontext, sub_ext));
}
return convertView;
}
although this code is insufficient. What I understood from this code is, you are using lazy loading for images, and mImageLoader must be running thread, which is setting image to viewHolder.
you can set imageInfo as tag in else part also.
....
else
{
//Display related file icon
viewHolder.image.setImageResource(FileUtil.getImageRelatedToFileType(mcontext, sub_ext));
viewHolder.image.setTag(genericDAO.id);
}
Inside ImageLoader, when new image is downloaded, just before you set new image to viewHolder please check for correct tag.

Facebook change image in page tab

I'm trying to change a facebook page tab image programatically. The idea is when my app will finish the instalation process, it will be change the image of the tab where it place it. After finish the process and give permissions to the app, The response of fb is "unautorized"
{"error":{"message":"(#300) Edit failure","type":"OAuthException","code":300}}
I searched about this error, the most close aproach was: https://developers.facebook.com/bugs/255313014574414/.
I tried the same CURL example described in the error and have the same response.
The strange thing is, when i tried change the image inside fb, it fails too. I think the problem is when the app ask permissions to install in the user page, and don't have enough permits.
But i don't know hot i chage the permit to authorize chage the image of the pagetab.
var fbparams = new Dictionary<string, object>();
string path = #"c:\test.jpg";
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
var picture = new FacebookMediaObject
{
//Tell facebook that we are sending image
ContentType = "image/jpeg",
//Give name to the image
FileName = "test"
};
//Create a new byteArray with right length
var img = tabImageInfo.Media;
//Convert the image content into bytearray
fs.Read(img, 0, img.Length);`enter code here`
//Close the stream
fs.Close();
//Put the bytearray into Picture
picture.SetValue(img);
//Add the image into parameters
fbparams.Add("custom_image", picture);
fb.Post(tab.id, fbparams);