Hướng dẫn thumbnail image php

I have found and modified a small php script for generating thumbnails

Nội dung chính

  • Prerequisites
  • A Real-World Example
  • The ThumbImage Class
  • The Example File
  • Learn PHP With a Free Online Course
  • How do I create a thumbnail image?
  • How do you add a thumbnail in HTML?
  • How do I create a thumbnail URL?
  • What are thumbnail photos?

$src = [isset[$_GET['file']] ? $_GET['file'] : ""];
$width = [isset[$_GET['maxwidth']] ? $_GET['maxwidth'] : 73];
$thname = "xxx";

$file_extension = substr[$src, strrpos[$src, '.']+1];

switch[strtolower[$file_extension]] {
     case "gif": $content_type="image/gif"; break;
     case "png": $content_type="image/png"; break;
     case "bmp": $content_type="image/bmp"; break;
     case "jpeg":
     case "jpg": $content_type="image/jpg"; break;

     default: $content_type="image/png"; break;

}

if [list[$width_orig, $height_orig, $type, $attr] = @getimagesize[$src]] {
    $height = [$width / $width_orig] * $height_orig;
}

$tn = imagecreatetruecolor[$width, $height] ;
$image = imagecreatefromjpeg[$src] ;
imagecopyresampled[$tn, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig];

imagejpeg[$tn, './media/'.$thname.'.'.$file_extension, 90];

It generates and saves thumbnails perfectly.

How can I display those thumbnails on the fly?

I tryed to add this at the bottom of a script

header['Content-Type: image/jpeg'];
imagegd[$image];

but it says The image cannot be displayed because it contains errors. What am I doing wrong?

Today, we’ll discuss how you could create thumbnail images in PHP with the help of the GD library.

When you’re working on projects that are related to media, more often than not you will need to create thumbnails from the original images. Also, if you’ve enabled image uploads on your website, it’s essential that you should never display the original images that are uploaded by users. That's because images uploaded by users could be of large size and will not be optimized for web display. Instead, you should always resize images before they're displayed on your website.

There are different tools that you can use to resize images in PHP, and we’re going to discuss one of the most popular options among them: the GD library. It’s one of the easiest ways to create image thumbnails on the fly.

Prerequisites

In this section, I'll go through the prerequisites for the example that we'll discuss later in this article.

Firstly, you should make sure that the GD library is enabled in your PHP installation. In a default PHP installation, the GD library should already be enabled. If you’re not sure about whether it's there, let's quickly check.

Create the info.php file with the following contents.

Chủ Đề