Re-size an image in using the Image class?
Is there a way to resize an image using the com.day.cq.wcm.foundation.Image class? I wanted to extend the foundation image componet and have it resize to a specific height and width. Is there a way to change the size of the image before you call image.draw(out) ?
You also don't want to insert you resizing efforts prior to calling the image.draw method. The draw method doesn't actually render the image, it draws the HTML img tag that your components print out. If you were to use the ImageHelper to get the layer and resize it that would not actually change the size of the image.
Now that img tag will contain a URL to the image, and that URL will generally look something like this (unless you have customized your image components):
/path/to/your/page/_jcr_content/par/textimage/image.img.jpg/1323947520848.jpg
This URL is going to trigger a script or servlet that will be responsible for rendering the image. In the example above because the textimage component extends the parbase component and because URL includes the img selector it will end up triggering the servlet at /libs/foundation/components/parbase/img.GET.java. If you go into CRXDE Lite you can go to this file and look at the source code of this servlet and see an example of how it uses the layer to resize the image if that author edited the image in the smart image widget.
You can also see example of servlets that resize and image ot specific preset sizes (as you want to do) you can look at /apps/geometrixx-outdoors/components/product/image/thumbnail.GET.java and /apps/geometrixx-outdoors/components/product/image/nav.GET.java.
So what you would want to do is something like this:
Create your own component at /apps/mysite/components/foo
Create a servlet at /apps/mysite/components/foo/bar.GET.java - put your logic to resize the image here based on some of the examples
Create your component JSP at /apps/mysite/components/foo/foo.jsp
Create your component's dialog and in this dialog include a smart image widget - make sure you store your image on component node, not a sub-node. If you store your image on a sub-node you need to make sure the sub-node includes the same resource type as your main node).
In your component JSP when you create your foundation Image object make sure to image.setSelector("bar") before you call image.draw()
That should result in an image URL that looks like /path/to/your/page/_jcr_content/par/textimage/image.bar.jpg/1323947520848.jpg
Those steps aren't tested - so I may have missed something or mistyped something, but it should point you in the right direction.
Similar Messages
-
How to use the Rectangle class to draw an image and center it in a JPanel
I sent an earlier post on how to center an image in a JPanel using the Rectangle class. I was asked to send an executable code which will show the malfunction. The code below is an executable code and a small part of a very big project. To simplifiy things, it is just a JFrame and a JPanel with an open dialog. Once executed the JFrame and the FileDialog will open. You can then navigate to a .gif or a .jpg picture and open it. What I want is for the picture to be centered in the middle of the JPanel and not the upper left corner. It is also important to stress that, I am usinig the Rectangle class to draw the Image. The region of interest is where the rectangle is created. In the constructor of the CenterRect class, I initialize the Rectangle class. Then I use paintComponent in the CenterRect class to draw the Image. The other classes are just support classes. The MyImage class is an extended image class which also has a draw() method. Any assistance in getting the Rectangle to show at the center of the JPanel without affecting the size and shape of the image will be greatly appreciated.
I have divided the code into three parts. They are all supposed to be on one file in order to execute.
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class CenterRect extends JPanel {
public static Rectangle srcRect;
Insets insets = null;
Image image;
MyImage imp;
private double magnification;
private int dstWidth, dstHeight;
public CenterRect(MyImage imp){
insets = getInsets();
this.imp = imp;
int width = imp.getWidth();
int height = imp.getHeight();
ImagePanel.init();
srcRect = new Rectangle(0,0, width, height);
srcRect.setLocation(0,0);
setDrawingSize(width, height);
magnification = 1.0;
public void setDrawingSize(int width, int height) {
dstWidth = width;
dstHeight = height;
setSize(dstWidth, dstHeight);
public void paintComponent(Graphics g) {
Image img = imp.getImage();
try {
if (img!=null)
g.drawImage(img,0,0, (int)(srcRect.width*magnification), (int)(srcRect.height*magnification),
srcRect.x, srcRect.y, srcRect.x+srcRect.width, srcRect.y+srcRect.height, null);
catch(OutOfMemoryError e) {e.printStackTrace();}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Opener().openImage();
class Opener{
private String dir;
private String name;
private static String defaultDirectory;
JFrame parent;
public Opener() {
initComponents();
public void initComponents(){
parent = new JFrame();
parent.setContentPane(ImagePanel.panel);
parent.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
parent.setExtendedState(JFrame.MAXIMIZED_BOTH);
parent.setVisible(true);
public void openDialog(String title, String path){
if (path==null || path.equals("")) {
FileDialog fd = new FileDialog(parent, title);
defaultDirectory = "dir.image";
if (defaultDirectory!=null)
fd.setDirectory(defaultDirectory);
fd.setVisible(true);
name = fd.getFile();
if (name!=null) {
dir = fd.getDirectory();
defaultDirectory = dir;
fd.dispose();
if (parent==null)
return;
} else {
int i = path.lastIndexOf('/');
if (i==-1)
i = path.lastIndexOf('\\');
if (i>0) {
dir = path.substring(0, i+1);
name = path.substring(i+1);
} else {
dir = "";
name = path;
public MyImage openImage(String directory, String name) {
MyImage imp = openJpegOrGif(dir, name);
return imp;
public void openImage() {
openDialog("Open...", "");
String directory = dir;
String name = this.name;
if (name==null)
return;
MyImage imp = openImage(directory, name);
if (imp!=null) imp.show();
MyImage openJpegOrGif(String dir, String name) {
MyImage imp = null;
Image img = Toolkit.getDefaultToolkit().getImage(dir+name);
if (img!=null) {
imp = new MyImage(name, img);
FileInfo fi = new FileInfo();
fi.fileFormat = fi.GIF_OR_JPG;
fi.fileName = name;
fi.directory = dir;
imp.setFileInfo(fi);
return imp;
}This is the second part. It is a continuation of the first part. They are all supposed to be on one file.
class MyImage implements ImageObserver{
private int imageUpdateY, imageUpdateW,width,height;
private boolean imageLoaded;
private static int currentID = -1;
private int ID;
private static Component comp;
protected ImageProcessor ip;
private String title;
protected Image img;
private static int xbase = -1;
private static int ybase,xloc,yloc;
private static int count = 0;
private static final int XINC = 8;
private static final int YINC = 12;
private int originalScale = 1;
private FileInfo fileInfo;
ImagePanel win;
/** Constructs an ImagePlus from an AWT Image. The first argument
* will be used as the title of the window that displays the image. */
public MyImage(String title, Image img) {
this.title = title;
ID = --currentID;
if (img!=null)
setImage(img);
public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h) {
imageUpdateY = y;
imageUpdateW = w;
imageLoaded = (flags & (ALLBITS|FRAMEBITS|ABORT)) != 0;
return !imageLoaded;
public int getWidth() {
return width;
public int getHeight() {
return height;
/** Replaces the ImageProcessor, if any, with the one specified.
* Set 'title' to null to leave the image title unchanged. */
public void setProcessor(String title, ImageProcessor ip) {
if (title!=null) this.title = title;
this.ip = ip;
img = ip.createImage();
boolean newSize = width!=ip.getWidth() || height!=ip.getHeight();
width = ip.getWidth();
height = ip.getHeight();
if (win!=null && newSize) {
win = new ImagePanel(this);
public void draw(){
CenterRect ic = null;
win = new ImagePanel(this);
if (win!=null){
win.addIC(this);
win.getCanvas().repaint();
ic = win .getCanvas();
win.panel.add(ic);
int width = win.imp.getWidth();
int height = win.imp.getHeight();
Point ijLoc = new Point(10,32);
if (xbase==-1) {
xbase = 5;
ybase = ijLoc.y;
xloc = xbase;
yloc = ybase;
if ((xloc+width)>ijLoc.x && yloc<(ybase+20))
yloc = ybase+20;
int x = xloc;
int y = yloc;
xloc += XINC;
yloc += YINC;
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
count++;
if (count%6==0) {
xloc = xbase;
yloc = ybase;
int scale = 1;
while (xbase+XINC*4+width/scale>screen.width || ybase+YINC*4+height/scale>screen.height)
if (scale>1) {
originalScale = scale;
ic.setDrawingSize(width/scale, height/scale);
/** Returns the current AWT image. */
public Image getImage() {
if (img==null && ip!=null)
img = ip.createImage();
return img;
/** Replaces the AWT image, if any, with the one specified. */
public void setImage(Image img) {
waitForImage(img);
this.img = img;
JPanel panel = ImagePanel.panel;
width = img.getWidth(panel);
height = img.getHeight(panel);
ip = null;
/** Opens a window to display this image and clears the status bar. */
public void show() {
show("");
/** Opens a window to display this image and displays
* 'statusMessage' in the status bar. */
public void show(String statusMessage) {
if (img==null && ip!=null){
img = ip.createImage();
if ((img!=null) && (width>=0) && (height>=0)) {
win = new ImagePanel(this);
draw();
private void waitForImage(Image img) {
if (comp==null) {
comp = ImagePanel.panel;
if (comp==null)
comp = new JPanel();
imageLoaded = false;
if (!comp.prepareImage(img, this)) {
double progress;
while (!imageLoaded) {
if (imageUpdateW>1) {
progress = (double)imageUpdateY/imageUpdateW;
if (!(progress<1.0)) {
progress = 1.0 - (progress-1.0);
if (progress<0.0) progress = 0.9;
public void setFileInfo(FileInfo fi) {
fi.pixels = null;
fileInfo = fi;
} -
Previewing an image before uploading it using the FileReference class
Previewing an image before uploading it using the FileReference class in flash player 3 not in SDK4
Previewing an image before uploading it using the FileReference class in flash player 3 not in SDK4
-
Previewing an image before uploading it using the FileReference class in flex 3
Previewing an image before uploading it using the FileReference class in flex 3 ?
hai,
when this code is used in my application ,i got the name of image and new frame is added each time .But image is not displayed.....
The code starts like this
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" initialize="init()" backgroundColor="white" width="100%" height="100%">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.messaging.Channel;
import mx.messaging.ChannelSet;
import mx.messaging.channels.AMFChannel;
import mx.rpc.events.ResultEvent;
import mx.controls.Image;
import spark.events.IndexChangeEvent;
import mx.managers.DragManager;
<mx:DataGridColumn headerText="Dimension Value" width="10" dataField="dimensionValue"/>
<mx:DataGridColumn headerText="Unit Nmae" width="10" dataField="dimensionUnitName"/>
</mx:columns>
</mx:DataGrid>
<mx:Spacer width="2%"/>
</mx:HDividedBox>
</mx:VBox>
<mx:Spacer height="0"/>
<mx:VBox width="100%">
<s:HGroup height="90" top="0" left="0" right="0" verticalAlign="justify" gap="10" paddingLeft="5" paddingRight="5" paddingTop="5" paddingBottom="5">
<s:Button id="btn_loader" top="5" bottom="24" width="100" label="load" click="loadImages()"/>
<s:Group width="100%">
<s:Group name="cl" top="0" left="0" bottom="0" width="20" mouseOver="//scroll_on(event)" mouseOut="//scroll_off(event)">
<s:BitmapImage source="@Embed('../assets/left.jpg')" top="0" left="0" bottom="0" right="0" fillMode="scale"/>
</s:Group>
<s:List id="imgList" skinClass="skins.ListSkin" top="-3" left="27" right="28" bottom="10"
dataProvider="{ImageCollection}" itemRenderer="Image_Render">
<s:layout>
<s:HorizontalLayout gap="0"/>
</s:layout>
</s:List>
<s:Group name="cr" top="0" right="0" bottom="0" width="20" mouseOver="//scroll_on(event)" mouseOut="//scroll_off(event)">
<s:BitmapImage source="@Embed('../assets/right.jpg')" top="-1" left="0" bottom="0" right="0" fillMode="scale"/>
</s:Group>
</s:Group>
</s:HGroup>
<s:SkinnableContainer id="dropCanvas" top="100" left="5" right="5" bottom="5" backgroundAlpha="1.0" alpha="1.0"
dragEnter="dropCanvas_dragEnterHandler(event)"
dragDrop="dropCanvas_dragDropHandler(event)" contentBackgroundColor="#914E4E" backgroundColor="#F7F7F7">
</s:SkinnableContainer>
</mx:VBox>
<mx:Spacer height="5"/>
</mx:VDividedBox>
</mx:Panel>
</mx:Canvas> -
Tracking Memory usage on iOS using the Stats class
I've been checking memory usage on an app I'm developing for iOS using the Stats class https://github.com/mrdoob/Hi-ReS-Stats ( http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c3-315cd077124319488fd-7fff.html#WS 948100b6829bd5a61637f0a412623fd0543-8000).
I added the Stats class to my project and redeployed and, yikes, memory usage reported in Stats creeps up (pretty slowly) even when there's nothing happening in the app (just showing a loaded bitmap).
To try and track down the issue I created a project with a test class that extends Sprite with just this single call in the constructor :-
addChild( new Stats() );
I deployed it to the device to check that it didn't gobble any memory.
But I was Suprised to watch the memory usage creep up and up (to approx 5) before some garbage collection kicked in and takes memory back down. I left it running and then it crept up again to over 7.5 this time before being kicked back down to just below 3.
So 2 related questions that I'd appreciate any feedback/observations/thoughts on :-
1 - Is this normal (i.e. memory creeping up when there's nothing other than Stats in the project) ?
2 - What is the best way to monitor memory usage within an app ? Is Stats good enough - is Stats itself causing the memory usage ?
All the best guys !Also see thread (http://forums.adobe.com/message/4280020#4280020)
My conclusions are :-
- If you run an app and leave it idle, memory usage gradually creeps up (presumably as memory is being used to perform calcs/refresh the display etc)
- Periodically the garbage collection kicks in and memory is brought back down
- This cycle could be in excess of 5 mins
Run with your real app and memory will increase and be released much more rapidly/regularly.
- It's probably worth performing initial checks by running on your desktop to iron out any initial problems -
How to use the different class for each screen as well as function.
Hi Experts,
How to use the different class for each screen as well as function.
With BestRegards,
M.Thippa Reddy.Hi ThippaReddy,
see this sample code
Public Class ClsMenInBlack
#Region "Declarations"
'Class objects
'UI and Di objects
Dim objForm As SAPbouiCOM.Form
'Variables
Dim strQuery As String
#End Region
#Region "Methods"
Private Function GeRate() As Double
Return Double
End Function
#End Region
Public Sub SBO_Appln_MenuEvent(ByRef pVal As SAPbouiCOM.MenuEvent, ByRef BubbleEvent As Boolean)
If pVal.BeforeAction = True Then
If pVal.MenuUID = "ENV_Menu_MIB" Then
End If
Else ' Before Action False
End If
End Sub
#End Region
End Class
End Class
Rgds
Micheal
Vasu Anna Regional Feeling a???? Just Kidding
Edited by: micheal willis on Jul 27, 2009 5:49 PM
Edited by: micheal willis on Jul 27, 2009 5:50 PM -
How to use the implementation class in propetty pallete
Hi,
I am using forms 10g....I have to insert horizontal scroll bar in text item..
I have only class files instead of jar files ...how cani place the class file instead of jar file...
How to use the implementation class in property palette to display the PJC
Thanks,
Ansaf.The Implementation Class must reflect the full name of the class. For instance, if the full class name is : xx.yyy.zz.class_name, then put this in the Implementation Class property of the corresponding item.
Also, the class must be stored in the equivalent directory structure, so that, in my example: <DEV_HOME>/forms/java/xx/yyy/zz
Francois -
Where we use the window class in the sql and how to use it
where we use the window class in the sql and how to use it
http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions004.htm#SQLRF06174
Regards
Etbin -
How to use the message class CL_BSP_MESSAGES in the event handler?
Hiii,
I need to use the message class CL_BSP_MESSAGES in the even handler, because I need to use the Condition co_cancel_event_prefix to prevent saving in the method
global_messages->add_message(
condition = co_cancel_event_prefix
message = TEXT-010
severity = cl_bsp_messages=>co_severity_error ).
dummy = ME->COMPONENT_ID ).
Can anybody explain me how to use this method?
Kind Regards,
Johnsolved
-
When Should I use the Inner Classes ?
When Should I use the Inner Classes ?
What is the advantage(s) and the disadvantage(s) ?When I use innerclasses?
1) Allmost allways when I need simple owner child behavior.
2) When I need a behaviour, that is quite small, and used only once, I make it anonymous inner class. For example specialised streams and threads.
3) Enumerations -
Excel opens and does not close when using the OI classes for some users...
Hello Experts,
I am using the OI classes(i_oi_container_control, i_oi_error, i_oi_document_proxy, i_oi_spreadsheet) to transfer Excel data to my itab. The problem we are encountering is that for some users the excel automatically opens and does not close. But in my case it is not opening so it is fine in my case. In my code I am already using the 'CLOSE_DOCUMENT' and 'RELEASE_DOCUMENT'.Viraylab,
Check by any case you set the parameter register_on_close_event of the method init_control? Dont set the parameter as it will look for the corressponding custom code in your program. Also try with the method release_all_documents.
Regards,
Kiran Bobbala -
Can I use the inner class of one containing class by the other class
Can I use the inner class of one containing class by the other class in the same package as the containing class
eg I have a class BST which has inner class Enumerator. Can I use the inner class from the other class in the same pacckage as BST?Inner classes do not share the namespace of the package of the containing class. Also they are never visible to other classes in the same package.Believe what you want, then, if you're going to make up your own rules about how Java works. For people interested in how Java actually works, here is an example that shows why that assertion is false:
package com.yawmark.jdc;
public class Outer {
public class Inner {
}And...
package com.yawmark.demo;
import com.yawmark.jdc.*;
public class Demo {
public static void main(String[] args) {
assert new Outer().new Inner() != null;
}~ -
Please help with executing the c-shell script by using the exe class
I try to use the exec class to execute a c-shell script in my java gui program like this. But I don't get anything when clicking on the start button.
here is my code:
Runtime r = Runtime.getRuntime();
r.exec("./DDMReportEvents");
./DDMReportEvents is the name of the c-shell script.I think Runtime.exec runs DOS batch files, but not Unix shell scripts.
Try:
r.exec("csh -c ./DDMReportEvents");
to get the shell to run the shell script. -
Determine the profile using the Authorization class?
Hi All,
How can i determine the profile using the authorization class?
Does anybody know which table and and field?
Regards,
LukeHi ,
try with these tables
agr_users
agr_1250
usr21
Pls let me know if you still need any more help.
Thanks and regards,
Rajeshwar. -
Load image using the loader class problem
Hi, I'm trying to load an image in a movieclip using using the following:
Load_image_btn.addEventListener(MouseEvent.CLICK,Load_image);
function Load_image(event:MouseEvent):void
var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("C:\Users\Amanda\Desktop\picture1"));
addChild(my_loader);
When I enter just "picture1" for the location it works, but like this it is giving me the following error: Error #2000: No active security context. How can I go about this, as I want to have a picture which in a separate location from that of the flash file?
I would also like to have the image located in a particular location (x,y) of the movieclip, is this possible? thanks in advance.I am using the following code:
function AddViewDetails(event:ListEvent):void
var mc:MovieClip=new Additional_Req_Info(); // where Additional_Req_Info is the class name
addChild(mc);
var clickedName:String = event.currentTarget.name;
trace (clickedName); /////prints Current_Req_List
var instanceName:String = clickedName + (Current_Req_List.selectedIndex + 1);
trace (instanceName); /////prints Current_Req_List1, Current_Req_List2, etc depending on list item selected
if(!getChildByName(instanceName)){
var classRef:Class=Class(getDefinitionByName(instanceName));
trace (classRef); ////not printed
var mc:MovieClip=new classRef();
mc.name=instanceName;
trace (mc.name); ////not printed
And its giving me the following error:
ReferenceError: Error #1065: Variable Current_Req_List1 is not defined.
at global/flash.utils::getDefinitionByName()
at Websiteversion4_Scene1_fla::MainTimeline/AddViewDetails()[Websiteversion4_Scene1_fla.Main Timeline::frame1:185]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at fl.controls::SelectableList/handleCellRendererDoubleClick()
How can I define the list items if they are dynamically generated i.e. at runtime? thanks!!! -
Using the fileReference class to upload image
I've been using the loadVars to upload text and pass
variables to php and onto the server. I've begun using the Flash
Filereference class so an image can be uploaded directly from a
Flash movie, not involving an html form. But within the
Filereference script I can't figure out how to pass a variable to
php as I did using loadVars method. I've tried a number of hit-miss
ways but they've all been misses.
Right now the path to save an image file is "hard-wired" into
the php script. This is the var that I want to pass.
thanks
The script is here if you need to take a peek:Someone else asked about this recently. I think the answer
you're after is here:
http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?forumid=15&catid=288&threadid =1317799
That's for POST data.
If you want to send additional GET data you could just append
it to the url.
Maybe you are looking for
-
Hi I need from pro. help me, i will deploy WLC 5500 and Network divide to LAN Connectivity which connect to end user, and DMZ which connect to servers my question is better to connect WLC close to end user Switch OR to DMZ area which a little bit far
-
Select records by date after first of next month
Hi I have an asp app accessing a SQL Server db and am getting myself into a tangle over dates. I have a date field ValidFromDt (smalldatetime) and another date field ValidUntilDt which respectively define when a record is valid from and until. I want
-
I have connected the output of my amplifier/discriminator which gives TTL output pulses of 20 ns rise time to my PCI6024E counter source, the other counter source is connected to a square wave generator such that when that counter gets to a certain v
-
Is there a way to track down a stolen imac without a findmymac app in it? My old imac was recently stolen and all I have is the serial number. I was told that with the ethernet ID I could possibly track it down once it connects back to internet. un
-
I just loaded ios7 and apart from its randomly faulty apps etc it looks awfull. Please tell me how I can go back to the previous version on my iPhone 4s. Thanks