Link to home
Start Free TrialLog in
Avatar of Coast Line
Coast LineFlag for Canada

asked on

Creating a Gallery with Watemarking all images in coldfusion 8

I have successfully created the gallery and they are being resized and stored in thumbnails folder as small files and images folder as large images.

ok now what i am trying to do here that oce i upload the images, it should automatically watremark the images small and big ones, vertically left aligned with my name copyrighted. i am running in troubles. here is my code for image uploading. multiple uploading is supported here.

one more thing. will that not effect the efficiuency of the pages.

how can i change my code below to make all my images to watermark.

<cfif IsDefined('form.upload')>
          <cfset message = "">
          <cfloop index="i" from="1" to="#variables.numberoffields#" step="1">
            <cfset filename = "form.file" & #i#>
            <cfif evaluate(variables.filename) neq "">
              <cfset Directory = "#Form.cato#">
              <cfset UploadDir = ExpandPath("gallery/images/#Directory#")>
              <cfset UploadDir2 = ExpandPath("gallery/thumbnails/#Directory#")>
              <cfset TAB = Chr(9)>
              <cfif NOT DirectoryExists(UploadDir)>
                <cfdirectory action="create" directory="#UploadDir#" mode="777">
              </cfif>
              <cfif NOT DirectoryExists(UploadDir2)>
                <cfdirectory action="create" directory="#UploadDir2#" mode="777">
              </cfif>
              <cfset show = replace(#variables.filename#,"%20","_","All")>
              <cffile action="UPLOAD" destination="#UploadDir#\" nameconflict="OVERWRITE" filefield="#show#" accept="image/*">
              <cfset Inpoint = #cffile.serverfile#>
              <cfimage action="resize" width="100" height="" source="#UploadDir#\#Inpoint#" 
              destination="#UploadDir2#\rr_#Inpoint#" overwrite="yes">
              <cfset outpoint = "rr_#Inpoint#">
              <cfquery datasource="#request.dsn#" >
		  		INSERT into imggall(img_thumb, description, category, 
		  		 littleimg)
		 		Values('#Inpoint#','Nothing','#form.cato#',
		  		,'#outpoint#')
		  </cfquery>
              <cfset message = message & ",File #i# was uploaded">
              <cfelse>
              <cfset message = message & ",File #i# was empty">
            </cfif>
          </cfloop>
          <cflocation url="index.cfm?action=gallery&msg=#trim(variables.message)#" addtoken="no">
          <cfelse>
          <h5>Start File Uploading</h5>
          <cfif isdefined("url.msg")>
            <div style="color:#FF0000;">
              <cfloop list="#url.msg#" index="i">
                <cfoutput>#i#</cfoutput><br />
              </cfloop>
            </div>
          </cfif>

Open in new window

Avatar of azadisaryev
azadisaryev
Flag of Hong Kong image

here's one way you can do it, which always worked very well for me:

you need to create 2 transparent PNG-24 images to be used as your watermark images: one for portrait photos and one for landscape photos.  these images will have your watermark image/text on a transparent backgroung.  PNG-24 is a good image format for these because CF works with them well and they support true colours with alpha transparency.

upload these images to your server.

now, after you upload and resize your photo, depending on if it is a portrait or landscape photo (you can programmatically find it out using ImageInfo() and comparing width and height returned), you will read appropriate watermark image into a cf variable using imageread() or <cfimage action="read"> and overlay it over your resized photo using imagePaste() function.

you will also want to set antialiasing on for your photo using ImageSetAntialiasing() and set its transparency to whatever value works best with your watermark image using ImageSetDrawingTransparency().

then write the combined image to disk using imagewrite() or <cfimage action="write">

that's pretty much it.

there are other ways to do it, too, like adding a watermark to an image dynamically only when a full-size image is previewed...

if you want a bit of a visual candy with cf image watermarking head over to http://www.photos-of-laos.org/
(that's one of the sites i made).  the watermarks there are added dynamically when a preview-size image is viewed only - the actual images are stored without any watermark so that if a registered and logged-in user is viewing the images, they see non-watermarked photos (saves on storage space... need to store only one photo instead of one with and one without watermark).

shout if you need more help.

Azadi
right now you are resizing photos and saving them to disk automatically because you are using DESTINATION attribute in <cfimage> tag.  you will need to use NAME attribute instead to save resized photo to a cf variable.
then set this var's antialiasing and transparency, read in your watermark image into another var, paste it over the first var, then write the var to disk as jpeg image.

Azadi
Avatar of Coast Line

ASKER

Well what i am trying to do is when i am resizing the image over this tag:
<cfimage action="resize" width="100" height="" source="#UploadDir#\#Inpoint#" 
              destination="#UploadDir2#\rr_#Inpoint#" overwrite="yes">


 my images which are big images are uploaded before this tag occurs for resizing. I want to hardcode the watermak and that is vertically i mean y-Axis to be 80% transparent, but banging my head wher i put it in between so it work smoothly. i though of something like this:
<!--- Create a blank image that is 500 pixels square. --->
<cfset myImage=ImageNew("",500,500)>
<!--- Set the background color for the image to white. --->
<cfset ImageSetBackgroundColor(myImage,"white")>
<!---Clear the rectangle specified on myImage and apply the background color. --->
<cfset ImageClearRect(myImage,0,0,500,500)>
<!--- Turn on antialiasing. --->
<cfset ImageSetAntialiasing(myImage)>
<!--- Draw the text. --->
<cfset attr=StructNew()>
<cfset attr.size=50>
<cfset attr.style="bold">
<cfset attr.font="Verdana">
<cfset ImageSetDrawingColor(myImage,"blue")>
<cfset ImageDrawText(myImage,"PROOF",100,250,attr)>
<!--- Write the text image to a file. --->
<cfimage action="write" source="#myImage#" destination="text.tiff" overwrite ="yes">
<!--- Use the text image as a watermark in the PDF document. --->
<cfpdf action="addwatermark" source="c:/book/1.pdf" image="text.tiff"
destination="watermarked.pdf" overwrite="yes">


i have above code but how i implement it
PDF??? for watermarking images? hmmm....

and looking more at your code - there is A LOT of wrong things in it...
i will try to work through it to fix things up.  will post results after a couple of beers...

Azadi

u drink lots of beer Dude!, but when i drink my brain get lost and do wired things same as here
hehe :)

btw, a question: your query that inserts your images into db - what exactly are you storing in each field? you have 'img_thumb' field and 'littleimage' field - what's the difference? which one is the large size image filename stored in? and btw2, if you save all your thumbnails as 'rr_[filename-of-large-image]' then you need to store only the large image filename in your db, and you can derive/create the thumbnail filename form the larg image filename...

Azadi
img_thumb stores my BIG images.
'littleimage' STORES my Thumbnails the images with rr_[imagename]. as far as rr_ is concerned i can rewrite the cfresize starement to as:
<cfimage action="resize" width="100" height="" source="#UploadDir#\#Inpoint#" 
              destination="#UploadDir2#\#Inpoint#" overwrite="yes">
this will create the thumbnails with same name but with the size i specified.



Dude any Help Please
ok, here's some code for you to try... but it comes with some assumptions:

IMPORTANT!

Attached code assumes that:
a) your server has all necessary cfimage patches and hotfixed installed.
b) you resize your uploaded photos to 500px wide (landscape-oriented) or 500px high (portrait-oriented) for full-size photos and to 100px wide (disrespective of orientation) for thumbnails. (change these values in the attached code if necessary)
c) you have created 2 .png images with transparent background to be used as your watermarks and these images are of appropriate width and height to fit into resized photos
d) these 2 images are named wm_h.png (horisontal/landscape watermark) and wm_v.png (vertical/portrait watermark).
e) these 2 images have been uploaded to gallery/wm/ folder on your server.

hth

Azadi

<cfset message = "">
<cfif structkeyexists(form, 'upload')>
	<cfset watermarkImgDir = expandpath("gallery/wm/")><!--- watermark images dir --->
	<!--- check if FORM.CATO is empy and create a random 6-character directory name if needed --->
	<cfif NOT len(trim(form.cato))>
		<cfset form.cato = replace(right(createuuid(), 6), "-", "", "all")>
	</cfif>
	<cfset ImgDir = expandpath("gallery/images/") & form.cato><!--- full-size images dir --->
	<cfset ThumbDir = expandpath("gallery/thumbnails/") & form.cato><!--- thumbnail images dir --->
	<!--- check that full-size and thumbnail images dirs exist and create if necessary--->
	<cfif NOT DirectoryExists(BaseImgDir & NewDir)>
		<cfdirectory action="create" directory="#ImgDir#" mode="777">
	</cfif>
	<cfif NOT DirectoryExists(BaseThumbDir & NewDir)>
		<cfdirectory action="create" directory="#ThumbDir#" mode="777">
	</cfif>
	<cfloop index="i" from="1" to="#variables.numberoffields#" step="1">
		<cfif len(trim(form['file' & i]))><!--- check that form.fileX field is not empty --->
			<!--- upload photo --->
			<cffile action="UPLOAD" destination="#ImgDir#" nameconflict="MAKEUNIQUE" filefield="file#i#" accept="image/*">
			<!--- save uploaded photo's server filename to a var --->
			<cfset Inpoint = cffile.serverfile>
			<!--- create new filename for uploaded photo with which resized images will be saved as --->
			<cfset NewFilename = rereplace(cffile.serverFileName, "[^[:alnum:]]", "_", "All") & cffile.serverFileExt>
			<!--- resize, add watermark and save full-size and thumbnail images --->
			<cfscript>
			myimg = ImageRead(ImageDir & '/' & Inpoint); //read the uploaded image into myimg variable
			myimgThumb = duplicate(myimg); //this duplicate image will be resized into thumbnail
			//check image orientation
			if (myimg.height gt myimg.width) {
				orientation = "v"; //vertical (portrait-oriented)
			} else {
				orientation = "h"; //horizontal (landscape-oriented)
			}
			ImageScaleToFit(myimgThumb, "100", "", "highQuality"); //scale image to 100px wide
			ImageWrite(myimgThumb, ThumbDir & 'rr_' & NewFilename, 0.8); //save thumbnail image
			if (orientation eq 'h') {
				//resize original image to 500px WIDE if landscape-oriented. change size as necessary
				ImageScaleToFit(myimg, "500", "", "highQuality");
			} else {
				//resize original image to 500px HIGH if portrait-oriented. change size as necessary
				ImageScaleToFit(myimg, "", "500", "highQuality");
			}
			wmimg = ImageNew(watermarkImgDir & "wm_" & orientation & ".png"); //read watermark image into variable
			ImageSetAntialiasing(myimg, 'on'); //set antialiasing on the image for better quality
			ImageSetDrawingTransparency(myimg, 25); //set image transparency so the applied watermark is semi-transparent. change 25 (=75% transparent) to another value if necessary
			ImagePaste(myimg, wmimg, (myimg.GetWidth()/2 - wmimg.GetWidth()/2), (myimg.GetHeight()/2 - wmimg.GetHeight()/2)); //overlay watermark over resized image, pasting it into center of image
			ImageWrite(myimg, ImageDir & NewFilename, 1); //save resized full-size watermarked image to disk
			</cfscript>
			<!--- insert image data into db --->
			<cfquery datasource="#request.dsn#" >
			INSERT INTO imggall
				(
					img_thumb
				, description
				, category
				, littleimg
				)
			VALUES
				(
					<cfqueryparam cfsqltype="cf_sql_varchar" value="#NewFilename#">
				, <cfqueryparam cfsqltype="cf_sql_varchar" value="Nothing">
				, <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.cato#">
				, <cfqueryparam cfsqltype="cf_sql_varchar" value="rr_#NewFilename#">
				)
			</cfquery>
			<!--- delete originally uploaded photo --->
			<cffile action="DELETE" file="#ImgDir & Inpoint#">
			<!--- append text to message --->
			<cfset message = message & ",File #i# was uploaded">
		<cfelse>
			<cfset message = message & ",File #i# was empty">
		</cfif>
	</cfloop>
	<cflocation url="index.cfm?action=gallery&msg=#trim(variables.message)#" addtoken="no">
<cfelse>
<!--- your form here --->
</cfif>

Open in new window

do i need to add something in my transparent PNG, i caanot find anything being written like ABC mark on watremark image
I modified a bit of code and as you said created two images, transparent and saved them as .gif extention. written nothing on it. i think i ahve to write something on it anyways that i will seee later. After some modification i ran the code:
<cfif structkeyexists(form, 'upload')>
        <cfset watermarkImgDir = expandpath("gallery/wm/")><!--- watermark images dir --->
        <cfset ImgDir = expandpath("gallery/images/") & form.cato><!--- full-size images dir --->
        <cfset ThumbDir = expandpath("gallery/thumbnails/") & form.cato><!--- thumbnail images dir --->
        <!--- check that full-size and thumbnail images dirs exist and create if necessary--->
        <cfif NOT DirectoryExists(ImgDir)>
                <cfdirectory action="create" directory="#ImgDir#" mode="777">
        </cfif>
        <cfif NOT DirectoryExists(ThumbDir)>
                <cfdirectory action="create" directory="#ThumbDir#" mode="777">
        </cfif>
        <cfloop index="i" from="1" to="#variables.numberoffields#" step="1">
                <cfif len(trim(form['file' & i]))><!--- check that form.fileX field is not empty --->
                        <!--- upload photo --->
                        <cffile action="UPLOAD" destination="#ImgDir#" nameconflict="MAKEUNIQUE" filefield="file#i#" accept="image/*">
                        <!--- save uploaded photo's server filename to a var --->
                        <cfset Inpoint = cffile.serverfile>
                        <!--- create new filename for uploaded photo with which resized images will be saved as --->
                        <cfset NewFilename = rereplace(cffile.serverFileName, "[^[:alnum:]]", "_", "All") & cffile.serverFileExt>
                        <cfdump var="#NewFileName#"><cfabort>
                        <!--- resize, add watermark and save full-size and thumbnail images --->
                        <cfscript>
                        myimg = ImageRead(ImgDir & '/' & Inpoint); //read the uploaded image into myimg variable
                        myimgThumb = duplicate(myimg); //this duplicate image will be resized into thumbnail
                        //check image orientation
                        if (myimg.height gt myimg.width) {
                                orientation = "v"; //vertical (portrait-oriented)
                        } else {
                                orientation = "h"; //horizontal (landscape-oriented)
                        }
                        ImageScaleToFit(myimgThumb, "100", "", "highQuality"); //scale image to 100px wide
                        ImageWrite(myimgThumb, ThumbDir & 'rr_' & NewFilename, 0.8); //save thumbnail image
                        if (orientation eq 'h') {
                                //resize original image to 500px WIDE if landscape-oriented. change size as necessary
                                ImageScaleToFit(myimg, "500", "", "highQuality");
                        } else {
                                //resize original image to 500px HIGH if portrait-oriented. change size as necessary
                                ImageScaleToFit(myimg, "", "500", "highQuality");
                        }
                        wmimg = ImageNew(watermarkImgDir & "wm_" & orientation & ".gif"); //read watermark image into variable
                        ImageSetAntialiasing(myimg, 'on'); //set antialiasing on the image for better quality
                        ImageSetDrawingTransparency(myimg, 25); //set image transparency so the applied watermark is semi-transparent. change 25 (=75% transparent) to another value if necessary
                        ImagePaste(myimg, wmimg, (myimg.GetWidth()/2 - wmimg.GetWidth()/2), (myimg.GetHeight()/2 - wmimg.GetHeight()/2)); //overlay watermark over resized image, pasting it into center of image
                        ImageWrite(myimg, ImgDir & NewFilename, 1); //save resized full-size watermarked image to disk
                        </cfscript>
                        <!--- insert image data into db --->
                        <cfquery datasource="#request.dsn#"  username="#request.user#" password="#request.pass#">
                        INSERT INTO imggall(img_thumb, description, category, littleimg)
                        VALUES(<cfqueryparam cfsqltype="cf_sql_varchar" value="#NewFilename#">, 
                        <cfqueryparam cfsqltype="cf_sql_varchar" value="Nothing">, 
                        <cfqueryparam cfsqltype="cf_sql_varchar" value="#form.cato#">, 
                        <cfqueryparam cfsqltype="cf_sql_varchar" value="rr_#NewFilename#">)
                        </cfquery>
                        <!--- delete originally uploaded photo --->
                        <cffile action="DELETE" file="#ImgDir & Inpoint#">
                        <!--- append text to message --->
                        <cfset message = message & ",File #i# was uploaded">
                <cfelse>
                        <cfset message = message & ",File #i# was empty">
                </cfif>
        </cfloop>
        <cflocation url="index.cfm?action=gallery&msg=#trim(variables.message)#" addtoken="no"> 
<cfelse>

</cfif>
I ran in trouble:
i got this error:


The web site you are accessing has experienced an unexpected error.
Please contact the website administrator. 

The following information is meant for the website developer for debugging purposes.  

Error Occurred While Processing Request  
The destination file should contain an extension, so that ColdFusion can determine the image format.  
Verify your inputs. The destination file should contain an extension, so that ColdFusion can determine the image format.  
  
The error occurred in C:\Inetpub\wwwroot\educationconsultant\admin\gallery.cfm: line 53
Called from C:\Inetpub\wwwroot\educationconsultant\admin\functions.cfm: line 25
Called from C:\Inetpub\wwwroot\educationconsultant\admin\index.cfm: line 50
 
51 :                         }
52 :                         ImageScaleToFit(myimgThumb, "100", "", "highQuality"); //scale image to 100px wide
53 :                         ImageWrite(myimgThumb, ThumbDir & 'rr_' & NewFilename, 0.8); //save thumbnail image
54 :                         if (orientation eq 'h') {
55 :                                 //resize original image to 500px WIDE if landscape-oriented. change size as necessary
 
 
Then i just Dumped the NewFileName and tried to check what is happening and i got this:

ani0a3jpg
while the exact image was :
ani0a3.jpg  
I tried making some modifications you see above but nothing seems to work.
You will see above:
i have somethings like:
  • Changed the Path for the Creating Images
  • Changed the ImageDir to
  • myimg = ImageRead(ImgDir & '/' & Inpoint); //read the uploaded image into myimg variable
  • Please see if i am doing something wrong here
oops, my fault... this:
<cfset NewFilename = rereplace(cffile.serverFileName, "[^[:alnum:]]", "_", "All") & cffile.serverFileExt>

should be this:
<cfset NewFilename = rereplace(cffile.serverFileName, "[^[:alnum:]]", "_", "All") & "." & cffile.serverFileExt>

also, i would NOT advise using GIF files for the watermark - cf mangles GIF files in all sorts of ways when you try to manipulated them using cf's image functions... PNG-24 format is the best for this. it is just like JPEG, but with transparency support.

Azadi
re transparent png: yes you obviously need something in there! what i meant by "2 .png images with transparent background" is images with something in them over a transparent background, i.e. see attached file.

Azadi
wm1.png
Thanks 
Having some issues:
  • Whn I upload images, thumbnail images stored outside the created folder with FolderName infront of rr_imagename something as: April2009rr_imageName
  • The above issue cause trouble in database, as it does not find the file in folder and also another the file name does not match.
  • I created a blank white image jpg and uploaded it. neither on the thumbnail nor on the big image, i found the watremark image.
  • The two watermarks are attched here, you call see
And Thanks For Created My Name :
Pretty Cool!!
:)

wm-h.png
wm-v.png
abc.jpg
> Whn I upload images, thumbnail images stored outside the created folder with FolderName infront of rr_imagename something as: April2009rr_imageName

i guess you must have edited the ThumbDir variable..

try changing this line:
ImageWrite(myimgThumb, ThumbDir & 'rr_' & NewFilename, 0.8);
to:
ImageWrite(myimgThumb, ThumbDir & '/rr_' & NewFilename, 0.8);
(added / in front of rr_)


> I created a blank white image jpg and uploaded it. neither on the thumbnail nor on the big image, i found the watremark image.

the code only adds watermark to the large image.
did you remember to change '.gif' to '.png' in this line:
wmimg = ImageNew(watermarkImgDir & "wm_" & orientation & ".gif"); <- should be ".png"!!!
?

Azadi
Ok, Counpleof things i did:
  • Change the path you specified, adding / to before rr_ solved the first problem.
  • I upload the blank file and still nothing written on the BIG image
  • the externtion from gif to PNG i had did it earlier before.
  • I did my Image in Fireworks saving as Flatten PNG using the options field to choose PNG 24. that whereever i see put the white color behind it.
  • Then i saved it in PNG 32.
  • I have null exp in Photoshop or i will say photoshop seems difficult for me to manage
Got this file attached

abc.jpg
i tried using your image send by you also, still it does not write on the image
hmm, just ran a full test with the code, and it worked just fine! except for one little thing:

you should delete the line

<cffile action="DELETE" file="#ImgDir & '/' & Inpoint#">

otherwise, unless the name of the file you upload contains non-alphanumeric characters, the resized large image is deleted... oops... sorry about that...

if it is still not working for you, can you post full code? just to make sure no errors crept in...
please post it using the "Attach Code Snippet" checkbox, otherwise it is a bit hard to read it...

Azadi
Almost Complete But still Someissues:
  • It upload the main file outside the dyanmically created folder.
  • Also it creates the file as: nameof folder and then filename, which is wrong for my database point of view
  • it shows as such
  • March 2009adrianasklenarikova05_1024x768
  • March_2009 should not come.
  • the file should move to images folder while it display the image outside the folder.
One last query, While file is attached which has watermak, i can always change the constrants to fit the watermark at the bottom, middle or top.
Right
> It upload the main file outside the dyanmically created folder

assuming these <cfset>s for ImgDir and ThumbDir look like this:

<cfset ImgDir = expandpath("gallery/images/") & form.cato><!--- full-size images dir --->
<cfset ThumbDir = expandpath("gallery/thumbnails/") & form.cato><!--- thumbnail images dir --->

the lines that write the images should look like this:

Thumbnail image: ImageWrite(myimgThumb, ThumbDir & '/rr_' & NewFilename, 0.8);
Full-size Image: ImageWrite(myimg, ImgDir & '/' & NewFilename, 1);

also, i see that you removed my lines of code that made sure FORM.CATO always contained text... you better then not forget to specify CATO in your form...

> Also it creates the file as: nameof folder and then filename
> March 2009adrianasklenarikova05_1024x768

see above. make sure the 2 code lines that write images are correct.

> the file should move to images folder while it display the image outside the folder

same as above, again.

Azadi
i solved the image in a folder mystery. but my image appears in center. can i change to the end of the image on right side or left side.
my image is attched

adrianasklenarikova04-1024x768.jpg
ASKER CERTIFIED SOLUTION
Avatar of azadisaryev
azadisaryev
Flag of Hong Kong image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks Bro! and Thanks For the Image MIne Image :)