Example analysis of how to change image size in php
Changing the size of pictures is a very common functional requirement. Let’s start studying the method of changing picture size in PHP.
First introduce a function written by myself.
<?php $imgsrc = "http://www.nowamagic.net/images/3.jpg"; $width = 780; $height = 420; resizejpg($imgsrc,$imgdst,$width,$height); function resizejpg($imgsrc,$imgdst,$imgwidth,$imgheight) { //$imgsrc jpg格式图像路径 $imgdst jpg格式图像保存文件名 $imgwidth要改变的宽度 $imgheight要改变的高度 //取得图片的宽度,高度值 $arr = getimagesize($imgsrc); header("Content-type: image/jpg"); $imgWidth = $imgwidth; $imgHeight = $imgheight; // Create image and define colors $imgsrc = imagecreatefromjpeg($imgsrc); $image = imagecreatetruecolor($imgWidth, $imgHeight); //创建一个彩色的底图 imagecopyresampled($image, $imgsrc, 0, 0, 0, 0,$imgWidth,$imgHeight,$arr[0], $arr[1]); imagepng($image); imagedestroy($image); } ?>
imagecopyresampled
imagecopyresampled -- Resample and resize part of the image.
int imagecopyresampled ( resource dst_im, resource src_im, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH)
imagecopyresampled() Copy a square in an image Regions are copied into another image, smoothly interpolating pixel values and thus, inter alia, reducing the size of the image while still maintaining great sharpness. dst_im and src_im are the identifiers of the target image and source image respectively. If the source and destination have different widths and heights, the image shrinks and stretches accordingly. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if dst_im and src_im are the same), but the results are unpredictable if the regions overlap.
Note: There is a problem because of the palette image limit (255+1 colors). Resampling or filtering an image often requires more than 255 colors, and an approximation is used in calculating the new resampled pixels and their colors. When trying to assign a new color to a palette image, if that fails we choose the closest (theoretically) calculated color. This is not always the visually closest color. This can produce weird results, such as blank (or visually blank) images. To bypass this problem, use a truecolor image as the target image, such as one created with imagecreatetruecolor().
Note: imagecopyresampled() requires GD 2.0.l or higher.
A simple example:
The code is as follows:
<?php // The file $filename = 'test.jpg'; $percent = 0.5; // Content type header('Content-Type: image/jpeg'); // Get new dimensions list($width, $height) = getimagesize($filename); $new_width = $width * $percent; $new_height = $height * $percent; // Resample $image_p = imagecreatetruecolor($new_width, $new_height); $image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // Output imagejpeg($image_p, null, 100); ?>
Example 2:
<?php // The file $filename = 'test.jpg'; // Set a maximum height and width $width = 200; $height = 200; // Content type header('Content-Type: image/jpeg'); // Get new dimensions list($width_orig, $height_orig) = getimagesize($filename); $ratio_orig = $width_orig/$height_orig; if ($width/$height > $ratio_orig) { $width = $height*$ratio_orig; } else { $height = $width/$ratio_orig; } // Resample $image_p = imagecreatetruecolor($width, $height); $image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Output imagejpeg($image_p, null, 100); ?>
There are two changes Image size method:
ImageCopyResized() function is valid in all GD versions, but its algorithm for scaling images is relatively rough.
ImageCopyResamples(), the image edges obtained by its pixel interpolation algorithm are relatively smooth. (But this function is slower than ImageCopyResized()).
The parameters of the two functions are the same, as follows:
The code is as follows:
imageCopyResampled(dest,src,dy,dx,sx,sy,dw,dh,sw,sh); imageCopyResized(dest,src,dy,dx,sx,sy,dw,dh,sw,sh);
Example:
<?PHP $src = ImageCreateFromJPEG('php.jpg'); $width = ImageSx($src); $height = ImageSy($src); $x = $widht/2; $y = $height/2; $dst = ImageCreateTrueColor($x,$y); ImageCopyResampled($dst,$src,0,0,0,0,$x,$y,$widht,$height); header('Content-Type : image/png'); ImagePNG($det); ?>
How to change the size of jpg image files in php
The code is as follows:
<? function resize_jpg($img,$w,$h){ // $thumb = imagecreate ($w, $h); $image = imagecreatefromjpeg($img); $imagedata = getimagesize($img); if ($h = "auto") $h = $w/($imagedata[0]/$imagedata[1]);//根据原图的纵横比得出高度! $thumb = imagecreatetruecolor ($w, $h); imagecopyresized ($thumb, $image, 0, 0, 0, 0, $w, $h, $imagedata[0], $imagedata[1]); imagejpeg($thumb); } //resize_jpg($file,$w,$h); resize_jpg("images/dsc01244.jpg",100,100); imagedestory($thumb); imagedestory($image); ?>
Function code:
<?php /* * 图片缩略图 * $srcfile 来源图片, * $rate 缩放比,默认为缩小一半,或者具体宽度象素值 * $filename 输出图片文件名jpg * 例如: resizeimage("zt32.gif",0.1); * 例如: resizeimage("zt32.gif",250 ); * 说明:调用时直接把函数的结果放在HTML文件IMG标签中的SRC属性里 */ function resizeimage($srcfile,$rate=.5, $filename = "" ){ $size=getimagesize($srcfile); switch($size[2]){ case 1: $img=imagecreatefromgif($srcfile); break; case 2: $img=imagecreatefromjpeg($srcfile); break; case 3: $img=imagecreatefrompng($srcfile); break; default: exit; } //源图片的宽度和高度 $srcw=imagesx($img); $srch=imagesy($img); //目的图片的宽度和高度 if($size[0] <= $rate || $size[1] <= $rate){ $dstw=$srcw; $dsth=$srch; }else{ if($rate <= 1){ $dstw=floor($srcw*$rate); $dsth=floor($srch*$rate); }else { $dstw=$rate; $rate = $rate/$srcw; $dsth=floor($srch*$rate); } } //echo "$dstw,$dsth,$srcw,$srch "; //新建一个真彩色图像 $im=imagecreatetruecolor($dstw,$dsth); $black=imagecolorallocate($im,255,255,255); imagefilledrectangle($im,0,0,$dstw,$dsth,$black); imagecopyresized($im,$img,0,0,0,0,$dstw,$dsth,$srcw,$srch); // 以 JPEG 格式将图像输出到浏览器或文件 if( $filename ) { //图片保存输出 imagejpeg($im, $filename ); }else { //图片输出到浏览器 imagejpeg($im); } //释放图片 imagedestroy($im); imagedestroy($img); } ?>
The above is the detailed content of Example analysis of how to change image size in php. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
