Gregory's Blog
long meetins stink

Sharing Video's to Facebook and Twitter

How to share videos on Facebook and Twitter from your own website

Note: if you're using Galaxie Blog, all that you need to do is upload your file and create the necessary XML Post Directives and Galaxie Blog will take care of the rest for you. This post is a technical how-to article on how I incorporated Plyr into Galaxie Blog. This is a continuation of my how to make the perfect social media sharing image series, but here we focus on using video and audio on Facebook and Twitter instead of sharing images.

Create the Video

In this video, I used a Battlestar Galactica preview made as a university project made by Bob. The 2004 Battlestar Galactica was one of my favorite Sci-Fi TV shows. The 2004 version of Battlestar Galactica is essentially a science fiction rendition of both the Genesis and Exodus stories, but the 10 plagues were instead caused by 6 different eerily human-like robots created by humans. OK, enough of the Sci-Fi stuff; time to get back to the substance of this article here.... Your own video should be created in mp4 format using the progressive HDTV 720p format. The final size should be 1280 x 720 (2048K bitrate).

Creating the images used by the social media platform along with the cover image

We still need to create several images to serve as the cover image. These images will cover the video until the video is loaded. If you reload this page, you will see a dark Battlestar Galacticaimage that will cover the video until the video is loaded. Once the video is loaded, the large arrow will show on top of the cover image.

  1. After you have created the video, create an image of the video by pressing the print screen. We will use this to create the images that we'll use in the image meta tags and to create a cover image for the video
  2. Crop the images using the same ratio and size formats as we did in part 2. The cover image for Facebook should be 1200x630, Twitter's dimensions are nearly the same at 1200x628. The cover image should be either .jpg or .png. WebP is not yet supported for social media sharing. I am providing resources and examples below.
  3. Once you have created and uploaded the images to your site, we need to create the essential open graph and Twitter tags and validate them on our web page as we did here:

You'll need to have an HTML5 capable Media Player on your website

It goes without saying that you'll also need to have an HTML5 Media Player to handle the video and audio formats on your own website. If you don't have an HTML5 media player, you can follow my steps to integrate Plyr on your own website.

Creating a separate player instance for Twitter

Unfortunately, Twitter can't read embedded videos from your own web page. Buried in Twitters player card documentation, you'll find that you also need to create a separate instance of your media player, and either point to the new instance, or an iframe. Importantly, the video must take up the full width of the page. This is how I solved this issue using Plyr. If you don't have Plyr, you'll have to use this approach with your own HTML5 media player. Here is the ColdFusion code that I used to create a new page with Plyr.

<!doctype html>
<!--- Note: this is a proof of concept page. This template will be revised. --->
<head>
	<!-- Plyr (our HTML5 media player) -->
	<InvalidTag src="/blog/common/libs/plyr/plyr.js"></script>
	<!-- Plyr css. -->
	<link rel="stylesheet" href="/blog/common/libs/plyr/plyr.css" />
</head>

<cfparam name="URL.videoUrl" default="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-1080p.mp4">
<cfparam name="URL.poster" default="https://gregoryalexander.com/blog/enclosures/twitter/blueMoonTrailer.jpg">
<cfparam name="URL.crossOrigin" default="false">
<style>
<!--- This must be set to full screen! --->
.mediaPlayer video {
	width: 100% !important
}
</style>

<div class="mediaPlayer">
	<video
		controls
		<cfif URL.crossOrigin eq true>crossorigin</cfif>
		playsinline
		poster="<cfoutput>#URL.poster#</cfoutput>"
		id="player1">
		<!-- Video files -->
		<!-- 1280x720 --->
		<source
			src="<cfoutput>#URL.videoUrl#?id=#createUuid()#</cfoutput>"
			type="video/mp4"
			size="720"
		/>

	</video>
</div>

This new instance of your player must be set to take the full width of the page. If it does not render the video using the full width of the page, Twitter will play the video at a much smaller resolution and the users will only see part of the video being played.

Creating the essential media meta tags

Twitter tagsThe following twitter tags must be set in the header of the page.

  • The first tag, the twitter:player meta tag is a directive that tells Twitter that we want to use the player card. When we are using just an image and not a video, we would use 'twitter:card' 'summary_large_image'
  • The next 4 tags are similar, if not identical, to the tags that we've covered in How to make the perfect social media sharing image - part 5. The only difference is that here we are using the image of the video that you have created in a previous step above.
  • I am using ColdFusion's createUuid function to generate the id element in the twitter:image. This is a trick that I learned to refresh the twitter preview after the initial twitter preview has been made.
<!-- Twitter meta tags. -->	
<!-- Note: we are using the twitter player card --->		
<script name="twitter:card" content="player" />
<script name="twitter:site" content="@https://gregoryalexander.com/blog" />
<script name="twitter:title" content="Plyr, a HTML5 media player, is incorporated into Galaxie Blog" />
<script name="twitter:description" content="Plyr is now the default HTML5 media player in Galaxie Blog" />
<!-- This is a picture taken of the video. The size of this image is 1200x628. --->
<script name="twitter:image" content="https://gregoryalexander.com/blog/enclosures/twitter/blueMoonTrailer.jpg?id=E2DC9DE6-9B6A-9736-EE1FFFD42B90FEC3" /> 

The next tags are used to tell Twitter how to play our fancy shiny video.

  • The "twitter:player" tag has the full URL to the minimal HTML5 Media Player that we covered above
  • The "twitter:player:width" for the recommended 720p video is 1280 pixels.
  • And the "twitter:player:height" for the recommended 720p video is 720 pixels.
<!-- Twitter player card meta types -->
<!-- The twitter video must be on a minimal page that just includes the video, and nothing else. -->
	
<script property="twitter:player" content="https://gregoryalexander.com/blog/videoPlayer.cfm?videoUrl=https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-720p.mp4&poster=https://gregoryalexander.com/blog/enclosures/twitter/blueMoonTrailer.jpg&id=E2DC9DE7-9749-288C-C9BA9EBE432D3203">
<script property="twitter:player:width" content="1280"></script>
<script property="twitter:player:height" content="720"></script>

Facebook Open Graph Tags

Facebooks' approach to video sharing is more streamlined than Twitter's. First, we don't need a minimal media player that plays the video on a full page. Facebook will glean the source of the video found in the og:video tag. The first 5 tags are identical to the open graph meta tags used for images. The only difference is that I added an extra fb:app_id meta tag. This key is not required; I am using my own developer key here as I want Facebook to know that this share is coming from a trusted source.

<!-- Open graph meta tags for Facebook. See notes. -->
<script property="og:image" content="https://gregoryalexander.com/blog/enclosures/facebook/blueMoonTrailer.jpg" /> 
<script property="og:site_name" content="Gregory's Blog" />
<script property="og:url" content="https://gregoryalexander.com/blog/2019/11/15/Plyr-a-HTML5-media-player-is-incorporated-into-Galaxie-Blog" />
<script property="og:title" content="Plyr, a HTML5 media player, is incorporated into Galaxie Blog" />
<script property="og:description" content="Plyr is now the default HTML5 media player in Galaxie Blog" />
<script property="fb:app_id" content="your facebook app id" />

The next set of tags informs Facebook that we are sharing a video.

  • The og:type tag indicates that we are using video.
  • The og:video:type tag indicates that we are using .mp4 as our video format. Facebook recommends .mp4 as its preferred video format.
  • The og:video, og:video:url, and og:video:secure_url should point to the same URL that is the source of the video. The video:type is not required, but I am including it in my code just to cover all of my bases here.
  • The og:video:width and height tags use the same width and height as Twitter using the 720p video format.
<!-- Video meta types -->
<script property="og:type" content="video.movie" />
<script property="og:video:type" content="video/mp4" />
<script property="og:video" content="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-720p.mp4" />
<script property="og:video:url" content="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-720p.mp4" />
<script property="og:video:secure_url" content="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-720p.mp4" /> 
<script property="og:video:width" content="1280" /> 
<script property="og:video:height" content="720" /> 

You can see an example of how this video was shared by following me on Twitter. Happy coding!

This entry was posted on November 18, 2019 at 2:00 PM and has received 1170 views.

How to make the perfect social media sharing image - part 6 Validation tools and tips


In this last post in this series, I will provide links to some social image sharing validator tools and provide a few tips and tricks that I learned along the way. After creating the proper social media images and fine-tuning the social media meta tags that are required, you can validate how each site will display your page using the tools below. Facebook Sharing DebuggerThe Facebook Sharing Debugger will validate your og meta tags and scrape the social media image. it's relatively straightforward to use. Just enter the URL of the page that you want to validate, and the debugger will scrape your page and show you if any errors were made. When you first enter the URL, it will take several seconds to generate the page, and if this page was not shared before, it will prompt you to fetch new information. Click on the button to fetch new information, and the debugger will list out data along with error information. The debugger will not immediately generate the Facebook sharing preview as it is crawling your page in the background, wait several minutes and refresh the page, and the image preview should be displayed. If you have errors indicating that you have missing tags, you can ignore these, as long as you have all of the essential tags. If you don't like the look of the images, you can make some changes, but come back here and regenerate the preview on the pages that you have shared the URL. If you're using Galaxie Blog, I have a utility tool in /common/utilities/cfimage.cfm that will allow you to reprocess the images quickly. For non-Galaxie Blog users, I have provided instructions below, and I placed the utility script on Git hub. Twitter Card ValidatorThe Twitter Card Validator is a bit easier to use, and it responds faster than the Facebook Sharing Debugger. Like Facebook, all that you need is to input your URL. After entering the URL, Twitters tool should immediately display your page preview. However, it is not easy to change the appearance of the preview after it has been made. I'll show you some tricks to re-create the preview. How to Regenerate a Twitter PreviewTwitter will cache your preview once the page has been shared, or a Twitter Card Preview has been made. However, it can be quite problematic to refresh the cache once made. I learned a few tricks and will show you a bulletproof way to change your preview if you have to make any changes. Go to the Twitter Open Graph meta tags in your page. Append something unique on the twitter:image tag like so. If you're using ColdFusion you can simply create a UUID. Other languages have the same capabilities. All you need to do is make sure that the URL is unique.

meta name="twitter:image" content="https://gregoryalexander.com/blog/enclosures/twitter/toby.jpg?id=#createUuid()#"

Once you have made the URL to the image unique, Twitter thinks that you have changed the image entirely, and will clear the cache and refresh the preview. Note: you'll have to get a Facebook and Twitter Developer Account to use these tools. Creating Social Media ImagesI have put a cfimage.cfm templateon GitHub for you to generate Social Media Images. I use this to generate social media images for my older posts. The usage is pretty simple. Upload the cfimage file to your server. then drop the original image in a enclosures folder, and create two new folders within the enclosures folder named twitter and facebook. In the socialMediaImagePath variable, put in the full image path for the type of image that you want to create. Go to the URL of your cfimage.cfm template with a browser, and the images will be saved underneath the '/enclosures/facebook' or '/enclosures/twitter' folders.

<!-- This is the only line that you should adjust --->
<cfset socialMediaImagePath="D:homegregorysblog.orgwwwrootenclosuresDSC_0518.JPG">
<!-- Consume the createSocialMediaImages(socialMediaImagePath, socialMediaImageType) function --->	
<cfset createSocialMediaImages(socialMediaImagePath,="" 'facebook',="" '')="">
<cfset createSocialMediaImages(socialMediaImagePath,="" 'twitter',="" '')="">

Other Social Media ValidatorsThere are other tools for validation for different media platforms, such as Twitters Post Inspector, and Pinterest Rich Pin's Validatorthat I will cover at a different time. Happy Coding!

This entry was posted on November 4, 2019 at 5:40 PM and has received 1379 views.

How to make the perfect social media sharing image - part 5 Essential Meta Tags


How to make the perfect social media sharing image - part 5 Essential Meta Tags

I have made several passes at improving the logic that Galaxie Blog uses to auto-generate the tags, and will share my experience with you. If you are using Galaxie Blog, the auto-generation of these tags is done for you.

Each social media site has its own rules for generating the meta tags. Facebook prefers open graph tags, Twitter can use the open graph tags, but it has a slew of its own proprietary tags, and Google +, LinkedIn, and Pinterest prefer schema markup tags, which I will not cover here.

Open Graph Tags

The following open graph tags are essential for Facebook

<meta property="og:image" content="URL to the social sharing image.">
<meta property="og:site_name" content="The site name (ie Galaxy Blog). " />
<meta property="og:url" content="The URL to the article" />
<meta property="og:title" content=" Must be 25 characters or less, especially for mobile" />
<meta property="og:description" content="Should be up to two sentences long, but under 30 characters for decent mobile rendering" />

The og:image:height and og:image:width tags are helpful, but not necessary. Facebook will correctly determine the proper image size as long as you stay within the Facebook recommendations.

Essential Twitter Tags

<meta name="twitter:card" content="summary_large_image">Use 'summary_large_image' if you're following along with this article
<meta name="twitter:site" content="@Site or article URL">
<meta name="twitter:title" content="The title of your site or article">
<meta name="twitter:description" content="Description, should be less than 200 characters">
<meta name="twitter:image" content="URL to the social sharing image.">
In the next article, I will go over some useful validation tools and share some tips and tricks with that I found.

This entry was posted on November 3, 2019 at 1:07 AM and has received 1247 views.

How to make the perfect social media sharing image - part 4 Image Examples


After the last entry, I wanted to show you the social media images that were created by ColdFusion. Each of these images match the exact recommended size and the ratio aspect that are recommended by the various social media platforms. I'll show you the actual images that were created, and how the social media platform displayed the images after I shared the previous article.

The images

The first image to the left is the original image that was uploaded. This is a picture of my dog, Toby, a super-smart, 13 y.o. bundle of energy running in the snow. The second image, in the middle, is the Facebook social media image, and the image to the right is the Twitter social media image. All of the social media images are copies of the original.

Galaxie Blog will automatically take the image that you want to post, and create Facebook and Twitter social media images that are sized per the social media's recommendations. The Facebook social media image is 1200 pixels wide, and 630 in height. Twitter is similar, but just a hair shorter. They are 1200 pixels wide, and 628 pixels in height.

How the page renders on social media sites

Below are the social media sites render the page when it is shared. The images below are actual screen shot's of the last post I shared in part 3 of this series. Again, the image to the left is the original. The middle image is how Facebook presents the site, and the image to the right is how Twitter displays the share.

Both Facebook and Twitter will take the images that were created by Galaxie Blog, and resize them into their own format. As long as the images either meet the maximum or minimum dimensions as they do here, the site presentation of the share will look good.

Note: this approach works for Slack and LinkedIn sites, but this is outside of the narrow Facebook and Twitter scope that I wanted to blog about.

Next up in this series, how to properly use the meta tags for social media sharing.

This entry was posted on November 2, 2019 at 1:45 AM and has received 1422 views.

How to make the perfect social media sharing image - part 3 Get the code...



In this post, I will share how I implemented logic to have Galaxie Blog automatically create social media sharing images for you when uploading an image for a given post.

Background

When a Galaxie Blog owner creates a post using the administrative interface, there is an option to upload an enclosure by clicking a Choose File button at the end of the add entry page. The interface is simple, when the Choose File button is clicked, it opens up a file browser and the user selects the image that they want to be displayed at the top of the post. In this post, the picture above is an abstract image that is 2200 pixels wide, and 1760 pixels in height. However, the social media images that the code below produces from this image will have different sizes that are optimized for both Facebook and Twitter. Galaxie Blog has always created a responsive image that automatically adjusts itself to fit on any modern device, however, I have now implemented logic that will manipulate the selected image and create both Facebook and Twitter social media images as well. Here is my approach...

Usage

To use this to create and save social media images, all that you need to do is invoke the createSocialMediaImages function below. It takes three arguments, the URL of the image that you want to perform operations on, the social media platform, and optionally, the Social Media Image Type. If the social media type argument is left blank (which is what I use in Galaxie Blog), the function will automatically determine the size and the proper aspect ratio. Here is the production code for Galaxie Blog that is working right now:

<!-- Set the path. --->
<cfset socialMediaImagePath="D:homegregoryalexander.comwwwrootlogenclosuresaspectRatio1.jpg">
<!-- Automatically generate social media images for Facebook, Twitter, Instagram and LinkedIn. --->
<cfset createSocialMediaImages(socialMediaImagePath,="" 'facebook',="" '')="">
<cfset createSocialMediaImages(socialMediaImagePath,="" 'twitter',="" '')="">
<cfset createSocialMediaImages(socialMediaImagePath,="" 'instagram',="" '')="">
<cfset createSocialMediaImages(socialMediaImagePath,="" 'linkedIn',="" '')=""> 

Logic Walkthrough

I am assuming that if you're reading this, you're someone with the technical skills that can read this and try it out, so I'll jump right in to briefly cover the core logic of this approach. For the sake of clarity, I will only cover how the logic creates Facebook social media images. Most of the logic for the other platforms is the same, and I'll provide the full code at the end of the article. Once the blog image is selected by the blog owner, Galaxie Blog will first get the width and height of the uploaded enclosure image that was just uploaded.

<cfimage action="info" source="#socialMediaImagePath#" structname="imageInfo">
</cfimage>

The logic will then compare the height and width of the original image and determine which type of image will be used. Essentially, are we going to use the largest image type specified by the social media platform, or the minimum depending upon the image that was just uploaded.

<cfcase value="facebook">
	<!--- Is the original image larger or smaller than Facebook's large image size? If larger, use the larger image dimensions specified by the social media platform. If the original image is smaller, use a smaller sized image. We are going to use similiar logic for every social media platform. --->
	<cfif imageInfo.width gte facebookSharedImageWidth and imageInfo.height gte facebookSharedImageHeight>
		<!--- Use the larger social media format. --->
		<cfset socialMediaImageType = "facebookSharedImage">
	<cfelse>
		<cfif imageInfo.width gte facebookLinkRectangleImageWidth and imageInfo.height gte facebookLinkRectangleImageHeight>
			<cfset socialMediaImageType = "facebookLinkRectangleImage">
		<cfelse><!---<cfif imageInfo.width gte facebookLinkRectangleImageWidth and imageInfo.height gte facebookLinkRectangleImageHeight>--->
			<!--- Use the facebookLinkSquareImage --->
			<cfset socialMediaImageType = "facebookLinkSquareImage">
		</cfif><!---<cfif imageInfo.width gte facebookLinkRectangleImageWidth and imageInfo.height gte facebookLinkRectangleImageHeight>--->
	</cfif>
</cfcase>

First, we will double-check the images again to make sure that the uploaded image has a larger size than the social media sharing image that we will create. If the uploaded image is larger, we'll set the width and height to match the larger image type. If the uploaded image is smaller than the largest recommended size, we will use the minimum size recommended by the social media platform, and we may set a pre-crop variable to true if necessary. We'll cover this logic next.

<cfcase value="facebookSharedImage">
	<!--- Is the original image larger or smaller than the large image size? If larger, use the larger image dimensions specified by the social media platform. If the original image is smaller, use the miniumum size. We are going to use the same logic for every social media type. --->
	<cfif imageInfo.width gte facebookSharedImageWidth and imageInfo.height gte facebookSharedImageHeight>
		<!--- Use the larger social media format. --->
		<cfset thisImageWidth = facebookSharedImageWidth>
		<cfset thisImageHeight = facebookSharedImageHeight>
	<cfelse>
		<!--- Use the rectangular facebook format. --->
		<cfset thisImageWidth = facebookLinkRectangleImageWidth>
		<cfset thisImageHeight = facebookLinkRectangleImageHeight>
		<cfset preCrop = true>
	</cfif>
</cfcase>

Resizing a copy of the original uploaded image

Next we'll check to see if the original image is twice as wide as the targetted social media size. If it is, or if the preCrop variable was set in the previous switch statements, we will create a copy of the original image, and then resize the new image. The code below illustrates this. I removed all of the code other than the Facebook code.

<cfif preCrop>

	<!--- Create a new image --->
	<cfset shareImage = imageNew(socialMediaImagePath)>

	<!--- Handle small images. --->
	<!--- This logic is only invoked for Facebook rectangle links. --->
	<cfif socialMediaImageType eq 'facebookLinkRectangleImage'>

		<!--- Resize the new image. For portrait images, we are going to resize the image to 550 pixels wide. --->
		<cfset imageResize(shareImage, 550, '')>
		<!--- We know the width of the new image that was just created (550), now get it's height --->
		<cfset shareImageWidth = imageGetHeight(shareImage)>
		<!--- Crop the resized image from the center (centerCrop(path/image, originalWidth, originalHeight, newWidth, newHeight). We don't need to determine an aspect ratio. It is a square. --->
		<cfset shareImage = centerCrop(shareImage, 550, shareImageWidth, thisImageWidth, thisImageHeight)>

	</cfif><!---<cfif (socialMediaImageType eq 'facebookLinkRectangleImage'>--->
</cfif>

Maintaining the aspect ratio using our nifty ColdFusion ratio calculator function

One of the most critical requirements is having the ability to resize images while maintaining the targeted aspect ratio. I could not find a ColdFusion function that did this, so I had to build my own. If you play around with manipulating images and aspect ratios, this type of function should belong in your own toolbox. Our ratioCalculator function below takes 3 arguments. The aspectRatioWidth and aspectRatioHeight arguments should match the recommended width and height of our targetted social media image that is indicated in the prior post. For the large Facebook Shared Image, the ratio aspect is 1200 pixels wide, and 630 pixels in height. We'll go ahead and plug these values in for the first two arguments as this is the aspect ratio that we want to keep, no matter what size we eventually resize the image to. The third argument is the newWidth argument. Here, the newWidth argument will either be: the original width of the uploaded image: or, the new width when we resized the image in the step above when the size of the uploaded image was twice the width of the recommended Facebook image size. The ratio calculator function will take these three values, and return the height that is needed to maintain the original aspect ratio. To get the new height of the image, all that we need to specify is the recommended width and height, provided by the social media platform, and the new width that we want to resize an image to be. The new width argument can be smaller, or larger, than the aspect ratio size. No matter what you plugin for the new width, the aspect ratio will be maintained.

<cffunction name="ratioCalculator" access="public" output="true" returnType="numeric" hint="This is used to determine the new dimensions needed to fit a certain width while maintaining the specified aspect ratio. I am using this to determine how to resize an image to meet the aspect ratio used by varius social media sites.">
	<cfargument name="aspectRatioWidth" required="yes" hint="Specify the original width of the image.">
	<cfargument name="aspectRatioHeight" required="yes" hint="Specify the original height of the image.">
	<cfargument name="newWidth" required="yes" hint="Specify the desired width of the new image.">

	<cfset newHeight = (arguments.aspectRatioHeight / arguments.aspectRatioWidth) * arguments.newWidth>

	<cfreturn newHeight>
</cffunction>

Cropping the images

The code has two cropping functions, centerCrop, and horizontalCrop. The centerCrop function is used when we have a landscape image, and the horizontalCrop function is used when using a portrait image. The centerCrop function takes five arguments, we need to specify the full path of the image, or the variable of the image if we are creating a new image using the newImage ColdFusion function. The original width and original height arguments using the social media recommended size. Here, we are using the large Facebook size of 1200 for the originalWidth, and 630 for the originalHeight. The fourth argument, width, is either the width of the uploaded image, or the width of the newly resized image, and finally, new height, which is provided by the ratioCalculator function that we just covered above. This function will crop the image from the center.

<cffunction name="centerCrop" access="public" output="true" returnType="string" hint="Used to crop an image with a desired size that is smaller both horizontally and vertically than the original image. This will crop the image from the center.">
	<cfargument name="imagePath" required="yes" hint="Provide either the full original path of the image, or the actual ColdFusion image using the newImage function.">
	<cfargument name="originalWidth" required="yes" hint="Provide the original width of the image.">
	<cfargument name="originalHeight" required="yes" hint="Provide the original width of the image.">
	<cfargument name="newWidth" required="yes" hint="Provide the desired width of the cropped image.">
	<cfargument name="newHeight" required="yes" hint="Provide the desired height of the new cropped image.">
	<!--- Local debugging carriage. If something goes awry, set this to true. --->
	<cfset debug = true>
		
	<!--- This algorithm was found at https://www.raymondcamden.com/2010/02/03/Cropping-to-the-center-of-an-image --->
	<cfset originalImage = "#arguments.imagePath#"> 
	<!--- Make a copy of the original image. --->
	<cfset croppedImage = imageNew(originalImage)> 
	<!--- Get the coordinates. We will subtract the orinal width minus the new width to grab the center of the new image.  --->
	<cfset xCoordinate = (originalWidth - newWidth) / 2>
	<cfset yCoordinate  = (originalHeight - newHeight) / 2>
			
	<cfif debug>
		<cfoutput>
			originalWidth: #originalWidth#<br/>
			originalHeight: #originalHeight#<br/>
			newWidth: #newWidth#<br/>
			newHeight: #newHeight#<br/>
			xCoordinate #xCoordinate#<br/> 
			yCoordinate" #yCoordinate#<br/>
		</cfoutput>
	</cfif>
			
	<!--- Crop the image. --->
	<cfset imageCrop(croppedImage, xCoordinate, yCoordinate, newWidth, newHeight)> 
			
	<!--- And return it. --->
	<cfreturn croppedImage>
</cffunction>

The horizontalCrop, used when we are uploading a portrait image, leaves the width intact, but crops the top and the bottom of the picture equally. This function takes three arguments, the imagePath (or the variable name of the new image when we use the imageNew ColdFusion function), the original height of the uploaded image, and the new height. I am using our ratioCalculator function to provide the new height again while maintaining the original aspect ratio recommended by the social media platform. Again, this example uses the large Facebook size of 1200 for the originalWidth, and 630 for the originalHeight.

<cffunction name="horizontalCrop" access="public" output="true" returnType="string" hint="Used to crop a horizontal image that has a horizontally size that is greater than the desired size of the new image. This will crop the image from the horizontal center.">
	<cfargument name="imagePath" required="yes" hint="Provide the full original path of the image.">
	<cfargument name="originalHeight" required="yes" hint="Provide the original width of the image.">
	<cfargument name="newHeight" required="yes" hint="Provide the desired height of the new cropped image.">
	<!--- Local debugging carriage. If something goes awry, set this to true. --->
	<cfset debug = true>
		
	<!--- This algorithm was found at https://www.raymondcamden.com/2010/02/03/Cropping-to-the-center-of-an-image --->
	<cfset originalImage = "#arguments.imagePath#"> 
	<!--- Make a copy of the original image. --->
	<cfset croppedImage = imageNew(originalImage)> 
	<!--- Get the coordinates. The x coordinate starts at 0. The image only needs to be cropped vertically.  --->
	<cfset xCoordinate = 0>
	<cfset yCoordinate  = (originalHeight - newHeight) / 2>
			
	<cfif debug>
		<cfoutput>
			originalHeight: #originalHeight#<br/>
			newHeight: #newHeight#<br/>
			xCoordinate #xCoordinate#<br/> 
			yCoordinate" #yCoordinate#<br/>
		</cfoutput>
	</cfif>
			
	<!--- Crop the image. --->
	<cfset imageCrop(croppedImage, xCoordinate, yCoordinate, newWidth, newHeight)>
			
	<!--- And return it. --->
	<cfreturn croppedImage>
			
</cffunction>

This is a rather long and complex post. In my next post, I'll provide some concise examples of social media images that this function creates.

Get the code

The code is published as a git hub repository. This component will also become a part of Galaxie Blog in the next release.

Further Reading

Some of the logic in the center crop function was taken from Raymond Camden's article at https://www.raymondcamden.com/2010/02/03/Cropping-to-the-center-of-an-image

This entry was posted on November 1, 2019 at 3:07 AM and has received 944 views.