I am trying to convert any image that a user uploads into the jpg format with a white background. However, I've noticed that when the user uploads a PNG image which contains transparency, ColdFusion is ruining the whole image. It almost looks like there's digital corruption going on.
So the user first provides a URL for where the image is located and cfhttp
is used to read it in:
<cfhttp url="http://pathtoimage/image.png" method="get" useragent="#CGI.http_user_agent#" getasbinary="yes" result="PageResult">
<cfimage name="UserImg" source="#PageResult.FileContent#" />
So now UserImg
is the image that the user wants to upload. Next we do the usual of setting antialiasing on and I also want the background to be white because the image could have a transparent background:
<cfset ImageSetAntialiasing(UserImg, "on")>
<cfset ImageSetBackgroundColor(UserImg, "white")>
The final stage is to write it to server as a jpg file:
<cfimage source="#UserImg#" action="write" destination="pathtoimages/userimage.jpg" overwrite="yes" format="jpg" />
The problem is that PNG images with transparency gets completely ruined. What should have a white background and be a clear jpg image ends up all blocky with a black background. Here's an example:
Original image:
After jpg conversion:
How do I work around this?
ImageSetBackgroundColor has no effect in that code. Per the documentation it:
Sets the background color for the ColdFusion image. The background color is used for clearing a region. Setting the background color only affects the subsequent ImageClearRect calls.
Since standard jpeg's do not support transparency, the partially transparent areas are essentially converted to black when the image is saved as a jpeg.
Instead, try pasting the transparent PNG onto a new image with a white background. Then do the conversion on the new image.
<!--- use "rgb" to make background opaque --->
<cfset UserImgCopy = ImageNew("", UserImg.Width, UserImg.Height, "rgb", "white")>
<cfset ImagePaste(UserImgCopy, UserImg, 0, 0)>
<cfset ImageWrite(UserImgCopy, "c:\path\userimage.jpg", true)>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With