使用gd库将图像裁剪_[视频]使用PHP和GD创建动态图像

使用gd库将图像裁剪

Creating your own images on-the-fly isn't hard at all, especially with the help of PHP and GD.

即时创建自己的映像并不困难,尤其是在PHP和GD的帮助下。

GD is a graphics library (http://www.boutell.com/gd/) , and PHP has an extension that gives easy access to the major GD functions, giving you the ability to use GD to generate images (JPEGs, GIFs, PNGs, etc) on-the-fly. This tutorial is aimed at people who come across the need for dynamic images, discover that PHP can do it with GD, but have a hard time understanding how to use it.

GD是一个图形库( http://www.boutell.com/gd/ ),而PHP具有扩展功能,可以轻松访问主要的GD功能,从而使您能够使用GD生成图像(JPEG,GIF, PNG等)。 本教程的目标读者是那些对动态图像有需求的人,他们发现PHP可以使用GD来实现,但是很难理解如何使用它。

The tutorial is offered in two versions, a video version, and a text-only version (although it may be helpful to see both).

本教程有两个版本,一个是视频版本,另一个是纯文本版本(尽管看这两个版本可能会有帮助)。

1.影片版本 (1. Video Version)

这个详细的视频将带您完成流程的每个步骤,并使用TrueType字体创建动态的,可重复使用的“文件夹选项卡”图像。

It will also cover some common mistakes and misunderstandings that many people face when working with dynamic images for the first time.

它还将涵盖许多人首次使用动态图像时遇到的一些常见错误和误解。

VIDEO:

视频:

http://www.screencast.com/t/wnXwbVRV http://www.screencast.com/t/wnXwbVRV

ZIP FILE CONTAINING FINAL CODE AND IMAGES:

包含最终代码和图像的ZIP文件:

gdarticle.zip gdarticle.zip

(You will need to remove the .txt extension from the files with that extension.)

(您将需要从具有该扩展名的文件中删除.txt扩展名。)

LINKS TO FUNCTIONS THAT I USED IN THE VIDEO:

链接到我在视频中使用的功能:

http://www.php.net/manual/en/function.imagettfbbox.php http://www.php.net/manual/zh/function.imagettfbbox.php http://www.php.net/manual/en/function.imagettftext.php http://www.php.net/manual/zh/function.imagettftext.php http://www.php.net/manual/en/function.imagecopy.php http://www.php.net/manual/zh/function.imagecopy.php http://www.php.net/manual/en/function.imagecopyresized.php http://www.php.net/manual/zh/function.imagecopyresized.php http://www.php.net/manual/en/function.imagecreate.php http://www.php.net/manual/zh/function.imagecreate.php http://www.php.net/manual/en/function.imagecreatefrompng.php http://www.php.net/manual/zh/function.imagecreatefrompng.php http://www.php.net/manual/en/function.imagecolorallocate.php http://www.php.net/manual/zh/function.imagecolorallocate.php

NOTES:

笔记:

1. In Part 1,  I use Photoshop to create some smaller images that I later use to make a nicer-looking tab. You don't need Photoshop - any image editor will do, and there are some good free ones out there, like Paint.NET and GIMP.

1.在第1部分中,我使用Photoshop创建一些较小的图像,以后将它们用于使外观更好看。 您不需要Photoshop-任何图像编辑器都可以,而且还有一些不错的免费软件,例如Paint.NET和GIMP。

2. I used a random font from my font library, but you can use ANY TrueType (.TTF) font file.

2.我从字体库中使用了随机字体,但是可以使用任何TrueType(.TTF)字体文件。

3. I use PNG files throughout the tutorial, but you can also use GIF, BMP, or JPEG formats, too (anything GD can support).

3.我在整个教程中都使用PNG文件,但是您也可以使用GIF,BMP或JPEG格式(GD可以支持的任何格式)。

4. I only used a small handful of GD functions. There are LOTS of things you can do with GD:

4.我只使用了少数GD函数。 您可以使用GD做很多事情:

http://www.php.net/manual/en/ref.image.php http://www.php.net/manual/zh/ref.image.php

5. GD -is- required to be installed on your server, and is usually found on most hosting providers that support PHP. On Windows servers, enabling GD is as simple as uncommenting the:

5. GD-必须安装在您的服务器上,通常可以在大多数支持PHP的托管提供程序中找到。 在Windows服务器上,启用GD就像取消注释一样简单:

extension=php_gd2.dll

扩展名= php_gd2.dll

line in your php.ini file. On Linux, you may need to either recompile PHP with the right options, or use a package manager to install GD support (it depends on how PHP was installed).

在您的php.ini文件中。 在Linux上,您可能需要使用正确的选项重新编译PHP,或者使用程序包管理器来安装GD支持(取决于PHP的安装方式)。

6. If your image looks broken, try accessing the image directly by its URL (instead of through an HTML document like I do in the video). Sometimes there are PHP errors that will show up in the image data that can help you figure out what's wrong.

6.如果您的图像看起来不完整,请尝试直接通过URL访问图像(而不是像视频中那样通过HTML文档访问)。 有时,图像数据中会显示PHP错误,可以帮助您找出问题所在。

2.文字版本 (2. Text Version)

一旦了解了一些基本概念,GD库就非常易于使用,我将为您解释每个概念:

What GD Can Do - Using GD, you can open an existing photo or image and change any part of it, whether it's changing the color of a single pixel, drawing a black square over the face of someone you don't like, or even adding a blur effect to the photo. You can also create a new image from scratch, and put whatever you want inside it, as if you were an artist painting onto a blank canvas.

GD可以做什么 -使用GD,您可以打开现有的照片或图像并更改其中的任何部分,无论是更改单个像素的颜色,还是在不喜欢的人的脸上绘制黑色正方形,甚至为照片添加模糊效果。 您也可以从头开始创建新图像,然后将所需的内容放在其中,就好像您是画家在空白画布上绘画一样。

What GD Cannot Do - GD is mostly limited by the amount of effort you want to put into it, but there ARE some things that GD is not really designed to do, so they're simply extremely difficult (or slow) to do. For example, you COULD write a million lines of code that reproduces a photo of someone pixel-by-pixel, but that's like painting a portrait by dipping a needle into paint and poking at the canvas. It CAN be done, but it's just not really GD's strength. However, with a little ingenuity, you'd be surprised at what you CAN pull off with GD.

GD无法做的事情 -GD主要受您要投入的工作量的限制,但是GD并不是真正设计来做的某些事情,因此它们做起来非常困难(或缓慢)。 例如,您可以编写一百万行代码来逐像素地复制某人的照片,但这就像通过将针浸入颜料中并在画布上戳戳来绘制肖像。 可以做到,但这并不是GD真正的强项。 但是,只要稍加匠心,您就会对GD所能带来的成就感到惊讶。

Image Resources - Whenever you look at an image on your computer, the viewing program opens up that image file, sucks in all the image data (so it knows what to show on your screen), and then closes the image file again. GD has to do the same thing in order to work with an image file. However, instead of just displaying the image data to you and closing, it copies the picture onto a virtual painting canvas so you can play with it. That virtual canvas is referred to as an image resource. So if you want to add a square onto the existing image, you tell GD to open the image file and give you the image resource. Then you tell it to paint a square onto the image resource / virtual canvas. When you're done, GD can save or display the results.

图像资源 -每当您在计算机上查看图像时,查看程序都会打开该图像文件,吸收所有图像数据(这样它就知道在屏幕上显示的内容),然后再次关闭该图像文件。 GD必须执行相同的操作才能处理图像文件。 但是,它不仅仅是将图像数据显示给您并关闭,而是将图片复制到虚拟绘画画布上,以便您可以使用它。 该图像资源 。 因此,如果您想在现有图像上添加一个正方形,则告诉GD打开图像文件并提供图像资源。 然后,您告诉它在图像资源/虚拟画布上绘制一个正方形。 完成后,GD可以保存或显示结果。

To create an image resource from an existing image, use the imagecreatefrom... functions, like:

要从现有图像创建图像资源,请使用imagecreatefrom ...函数,例如:

imagecreatefrompng()

imagecreatefrompng()

http://www.php.net/manual/en/function.imagecreatefrompng.php http://www.php.net/manual/zh/function.imagecreatefrompng.php
$im = imagecreatefrompng("reunion.png");

imagecreatefromjpeg()

imagecreatefromjpeg()

http://www.php.net/manual/en/function.imagecreatefromjpeg.php http://www.php.net/manual/zh/function.imagecreatefromjpeg.php
$im = imagecreatefromjpeg("vacation.jpg");

imagecreatefromgif()

imagecreatefromgif()

http://www.php.net/manual/en/function.imagecreatefromgif.php http://www.php.net/manual/zh/function.imagecreatefromgif.php
$im = imagecreatefromgif("myPicture.gif");

Or, to create a new, blank image resource, just use imagecreate():

或者,要创建一个新的空白图像资源,只需使用imagecreate()

http://www.php.net/manual/en/function.imagecreate.php http://www.php.net/manual/zh/function.imagecreate.php
$im = imagecreate(300,150); // Create a 300 x 150 image

X & Y Coordinates - In real life, if someone told you to paint a sun at the top of your picture, you would know generally where to put it. Computers, as with most things, are far more precise. You can't tell GD to just paint a yellow circle at the top of your picture - you have to tell it the EXACT location where you want the yellow circle to go. This is done with coordinates. A set of coordinates is simply two numbers, referred to as X and Y, and might look like: 54, 23. In that example, 54 is the X coordinate, and 23 is the Y coordinate, and they indicate an exact location on our virtual canvas.

X&Y坐标 -在现实生活中,如果有人告诉您在图片的顶部绘制太阳,您通常会知道将其放置在何处。 与大多数事物一样,计算机要精确得多。 您不能告诉GD仅在图片的顶部绘制一个黄色圆圈-您必须告诉它希望该黄色圆圈到达的确切位置。 这是通过坐标完成的 一组坐标只是两个数字,称为X和Y,可能看起来像:54、23。在该示例中,54是X坐标,而23是Y坐标,它们指示了我们上的确切位置虚拟画布。

If you imagine your virtual painting canvas and put a giant grid of squares on it, you would probably say that the very first square is the one in the top-left corner. This is exactly how coordinates work in GD. Coordinates start at 0 and go up the size of your image. So if you had an image that was 300 pixels wide and 150 pixels tall, then your X coordinate could be any number between 0 and 299 (not 300, because we start at 0). Likewise, the Y coordinate could be anything from 0 to 149. If you haven't guessed already, the coordinates 0, 0 always refer to the top-left corner of your image. In our example image, the coordinates 299, 149 would refer to the bottom-right corner.

如果您想象您的虚拟绘画画布并在其上放了一个巨大的正方形网格,您可能会说第一个正方形是左上角的那个。 这正是GD中坐标的工作方式。 坐标从0开始,并增大图像的大小。 因此,如果您的图像宽300像素,高150像素,那么您的X坐标可以是0到299之间的任何数字(不是300,因为我们从0开始)。 同样,Y坐标可以是0到149之间的任何值。如果您还没有猜到,则坐标0、0总是指图像的左上角。 在我们的示例图像中,坐标299、149将指向右下角。

Color Allocation - Let's talk about the painting canvas again. If you've ever seen an old picture of a classic painter, then you've probably seen them holding a thin, circular wooden board called a palette (if you're not sure what I'm talking about, use Google Images to search for "painting palette"). The palette holds the different colors of paint that the artist uses. All computer images have a palette, as well, and it works the same way (which is why they named it a palette). After all, every image is just a bunch of pixels of different colors. The palette of a computer image is just a giant, virtual version of that wooden board, and holds anywhere from 2 colors to millions of them.

颜色分配 -让我们再次谈论绘画画布。 如果您曾经看过经典画家的旧照片,那么您可能已经看到他们拿着一块称为调色板的圆形木板(如果您不确定我在说什么,请使用Google图片搜索用于“绘画调色板”)。 调色板包含艺术家使用的不同颜色的颜料。 所有计算机映像也都具有一个调色板,并且其工作方式相同(这就是为什么它们将其命名为调色板)的原因。 毕竟,每个图像只是一堆不同颜色的像素。 计算机图像的调色板只是该木板的巨大虚拟版本,可容纳2种颜色到数百万种颜色。

When you want to paint something onto a virtual canvas, you almost always need to specify a color. This is done by first allocating a color to our palette, giving you a color resource. When it comes time to paint, we just provide that color resource to the "painting" function (whichever one you're using).

当您想在虚拟画布上绘画时,几乎总是需要指定一种颜色。 首先,为我们的调色板分配颜色,为您提供颜色资源 。 当需要绘画时,我们只需将该颜色资源提供给“绘画”功能(无论您使用哪种)。

Color Combinations - Your basic color is made up of a certain amount of Red, an amount of Green, and an amount of Blue (hence the acronym RGB). Each amount can be a number from 0 to 255. White is made up of the maximum value of all three, so it is 255 Red, 255 Green, and 255 Blue. Black, on the other hands, is 0 of everything. You can get a bright green color with 0 Red, 255 Green, and 0 Blue. From there, you can figure out that you have access to quite a few combinations of colors (16,581,375 to be exact).

颜色组合 -您的基本颜色由一定数量的红色,一定数量的绿色和一定数量的蓝色(因此缩写为RGB)组成。 每个数量可以是0到255之间的数字。白色由这三个值的最大值组成,因此它是255红色,255绿色和255蓝色。 另一方面,黑色为所有事物的0。 您可以使用0红色,255绿色和0蓝色获得亮绿色。 从那里,您可以发现您可以使用多种颜色组合(准确地说是16,581,375种)。

To allocate a color with a specific color combination, use imagecolorallocate():

要分配具有特定颜色组合的颜色,请使用imagecolorallocate()

http://www.php.net/manual/en/function.imagecolorallocate.php http://www.php.net/manual/zh/function.imagecolorallocate.php
$white = imagecolorallocate($im, 255, 255, 255);

Resizing / Resampling - One of GD's strengths is taking an existing image and changing it's size. This might just be a simple enlargement of a photo or a reduction, or maybe you're stretching out an image. You can do it in one of two ways - with resizing or resampling. Resizing is pretty self-explanatory - GD takes an image and stretches it out to the size you want. Resampling does the same thing but goes a bit further and tries to "smooth out" parts of the image so you don't end up with blocky, pixelated results. Resampling usually works better when you're resizing photos with lots of colors (although it is slower than resizing), while resizing usually works best when you're dealing with either a few colors or else you don't want the "smoothing out" effect. (You can also just copy different parts from different pictures and put them all together into one new image without resizing.)

调整大小/重新采样-GD的优势之一是拍摄现有图像并更改其大小。 这可能只是照片的简单放大或缩小,或者您可能正在拉伸图像。 您可以通过以下两种方式之一进行操作-调整大小或重新采样。 调整大小是不言自明的-GD会拍摄图像并将其拉伸到所需的大小。 重采样具有相同的作用,但会做得更远,并尝试“平滑”图像的某些部分,以免最终出现块状像素化的结果。 当您调整带有多种颜色的照片的大小时,重采样通常效果更好(尽管比调整大小要慢),而当您处理几种颜色或者不想“平滑”时,重新调整大小通常效果最佳。影响。 (您也可以只复制不同图片中的不同部分,并将它们放在一起成为一个新图像,而无需调整大小。)

If you want to copy an image (or part of an image) without resizing or resampling, use imagecopy():

如果要复制图像(或图像的一部分)而不调整大小或重新采样,请使用imagecopy()

http://www.php.net/manual/en/function.imagecopy.php http://www.php.net/manual/zh/function.imagecopy.php

To copy using resizing, use imagecopyresized():

要使用调整大小进行复制,请使用imagecopyresize()

http://www.php.net/manual/en/function.imagecopyresized.php http://www.php.net/manual/zh/function.imagecopyresized.php

To copy with resampling, use imagecopyresampled():

要使用重新采样进行复制,请使用imagecopyresampled():

http://www.php.net/manual/en/function.imagecopyresampled.php http://www.php.net/manual/zh/function.imagecopyresampled.php

NOTE: Check out the code in the attached ZIP file at the end of this article for examples on how to use the copy and copyresized functions.

注意:在本文结尾处,请查看随附的ZIP文件中的代码,以获取有关如何使用copy和copyresize函数的示例。

Content-Type: - Let's say you've created a dynamic image and you're now ready to display it to the user. These dynamic images are almost always viewed through an internet browser like Firefox or Internet Explorer. Some browsers can look at all the binary data gibberish and make a guess at what it is (is it a JPEG or a GIF? Or maybe a PNG?), but not all of them have that ability. Imagine trying to read a Spanish book as if all the words were supposed to be English - none of the words would make sense! But if you were told to read it in Spanish (and if you knew Spanish), then you could read and understand the book. So before we start spewing out all of our image data to the browser, we can tell the browser what kind of image we're about to send. That way, all browsers can be prepared to take the data and make sense of all of it.

Content-Type: -假设您已经创建了一个动态图像,现在可以将其显示给用户了。 这些动态图像几乎总是通过Firefox或Internet Explorer等Internet浏览器查看的。 一些浏览器可以查看所有的二进制数据,然后对其进行猜测(是JPEG还是GIF?或者是PNG?),但是并不是所有的浏览器都具有这种能力。 想象一下,试图读一本西班牙书,好像所有的单词都应该是英语一样-这些单词都没有意义! 但是,如果您被告知要用西班牙语阅读(并且您知道西班牙语),那么您可以阅读和理解这本书。 因此,在我们开始将所有图像数据喷出到浏览器之前,我们可以告诉浏览器我们将要发送哪种图像。 这样,所有浏览器都可以准备好获取数据并理解所有数据。

header("Content-type: image/png");

Fonts - One of the most frequently-used features of GD is the ability to write text onto an image, using any TrueType font (fonts that end in the .TTF extension) that you have on your system. The most common problem people face here is simply not putting the font file into a place where GD can get to it. During development, I usually copy the font file into the same folder as my dynamic image. Once I get it working, I can move the font file into its final location and adjust my script to look for it in that new location.

字体-GD最常用的功能之一就是能够使用系统上具有的任何TrueType字体(以.TTF扩展名结尾的字体)将文字写到图像上。 人们在这里面临的最常见问题就是根本没有将字体文件放到GD可以到达的地方。 在开发过程中,通常将字体文件复制到动态图像所在的文件夹中。 一旦可以正常工作,就可以将字体文件移至最终位置,并调整脚本以在新位置中查找它。

Bounding Boxes - The other most common problem people face with working with text is dealing with sizes. If you create an image that is 300 pixels wide, and then you try to write a really long sentence in a big font, then the text is going to disappear off the canvas / image, and you're not going to be able to see it. The image does not magically expand to hold everything - that is something you are responsible for doing, and that is why you are giving the bounding box tool. For simplicity's sake, I like to call it the boundary box instead, since it feels a little more accurate. To explain the bounding box, look for any word on this page that is in a nice, big font, and just remember what it looks like. Now imagine you could stretch a rubber band around the word, and after you did that, the rubber band suddenly spoke to you and said, "This word is 50 pixels wide and 20 pixels tall." That is what a bounding/boundary box is, except instead of a rubber band, it's an invisible rectangle.

边界框 -人们在处理文本时遇到的另一个最常见的问题是处理大小。 如果您创建一个300像素宽的图像,然后尝试用大字体写一个很长的句子,则文本将从画布/图像上消失,并且您将无法看到它。 图像无法神奇地扩展以容纳所有内容-这是您要负责的事情,这就是为什么要使用边界框工具。 为了简单起见,我喜欢将其称为边界框 ,因为它感觉更准确一些。 为了解释边界框,请在此页面上查找任何带有大字体的漂亮单词,并记住它的外观。 现在想象一下,您可以在单词周围拉一条橡皮筋,然后,橡皮筋突然对您说:“这个单词宽50像素,高20像素。” 这就是边界/边界框,除了橡皮筋,它是一个不可见的矩形。

You can give GD a font name, a font size, and a word (or words), and tell it to create a bounding box. In return, GD gives you an array of coordinates, but 99% of the time, you'll just want two coordinates - the X and the Y coordinate of the bottom-right corner (which would also tell you how wide/tall the box is). Using a bounding box, you can increase the size of your new image to fit all of the text (if that's what you want to do).

您可以给GD一个字体名称,一个字体大小和一个(或多个)单词,并告诉它创建一个边界框。 作为回报,GD为您提供了一个坐标数组,但是在99%的时间中,您只需要两个坐标-右下角的X和Y坐标(这也可以告诉您盒子的宽/高)是)。 使用边框,您可以增加新图像的大小以适合所有文本(如果要这样做)。

The PHP function for creating a bounding box is imagettfbbox():

用于创建边界框PHP函数是imagettfbbox()

http://www.php.net/manual/en/function.imagettfbbox.php http://www.php.net/manual/zh/function.imagettfbbox.php
//
$boundingBox = imagettfbbox($fontSize, 0, "myFont.ttf", "How big is this text?");
$textWidth = $boundingBox[4]; // 4 is the X coordinate for a right corner of the bounding box
//

To actually write text onto an image, use imagettftext():

要将文字实际写到图像上,请使用imagettftext()

http://www.php.net/manual/en/function.imagettftext.php http://www.php.net/manual/zh/function.imagettftext.php
imagettftext($im, $size, 0, $X, $Y, $blue, $font, "Some text");

Fonts and Y Coordinates - The third (and last) most common text-relaed problem occurs when people test out their fonted, text-writing code and use the coordinates 0, 0 for the position of their text (and they don't see anything happening). However, writing text onto an image is like writing on a lined piece of notebook paper. You write just above that thin little line. So when you're writing text on an image, the X coordinate still acts normal, but the Y coordinate represents the line UNDERNEATH your text. So coordinates 0, 0 will still work, but you won't see anything because the BOTTOM of the text is at the 0 Y coordinate.

字体和Y坐标 -当人们测试其字体,文本编写代码并使用坐标0、0作为文本位置时(他们看不到任何东西),这是第三(也是最后一个)最常见的文本相关问题发生)。 但是,将文本写到图像上就像在衬砌的笔记本纸上书写一样。 您

Adjusting is pretty simple. When you're writing text, you also specify a font size. This font size is simply how tall the font can be in pixels (easiest seen with upper-case letters). So with a font size of 12, your upper-case letter M will be 12 pixels tall. That said, if you want the text to appear at the very top of your image, all you need to do is start at your font size value (e.g. 12) instead of 0 for your Y coordinate. If you're trying to do any math to calculate a Y coordinate, just keep that little offset in mind, and you'll be in the clear.

调整非常简单。 在编写文本时,还可以指定字体大小。 该字体大小就是字体的高度(以像素为单位)(用大写字母最容易看到)。 因此,如果字体大小为12,则大写字母M的高度将为12个像素。 就是说,如果您希望文本出现在图像的最上方,您要做的就是从字体大小值(例如12)开始,而不是从Y坐标开始为0。 如果您想做任何数学运算来计算Y坐标,只需记住一点点偏移量,就可以了。

The video tutorial tries to illustrate many of these concepts and take you through the coding of them, but now that you know the basic concepts, you should be able to take my attached example and figure out what it's doing (and play around with it).

该视频教程尝试说明其中的许多概念,并带您完成它们的编码,但是既然您已经了解了基本概念,那么您应该能够以我所附的示例并弄清楚它在做什么(并进行尝试)。 。

ZIP FILE CONTAINING EXAMPLE CODE AND IMAGES:

包含示例代码和图像的ZIP文件:

gdarticle.zip gdarticle.zip

You can do some pretty cool things with PHP and GD, so make good use of your new tools!

您可以使用PHP和GD做一些很酷的事情,所以请充分利用您的新工具!

翻译自: https://www.experts-exchange.com/articles/1898/Video-Create-Dynamic-Images-with-PHP-and-GD.html

使用gd库将图像裁剪

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值