Saya ingin menulis beberapa kode PHP yang secara otomatis mengubah ukuran gambar apa pun yang diunggah melalui formulir menjadi 147x147px, tetapi saya tidak tahu bagaimana melakukannya (saya seorang pemula PHP relatif).
Sejauh ini, saya mendapatkan gambar yang berhasil diunggah, tipe file dikenali dan nama dibersihkan, tetapi saya ingin menambahkan fungsionalitas pengubahan ukuran ke dalam kode. Sebagai contoh, saya memiliki gambar percobaan yang berukuran 2.3MB, dan berdimensi 1331x1331, dan saya ingin kodenya memperkecil ukurannya, yang menurut saya akan secara dramatis memampatkan ukuran file gambar juga.
Sejauh ini, saya mendapatkan yang berikut:
if ($_FILES) {
//Put file properties into variables
$file_name = $_FILES['profile-image']['name'];
$file_size = $_FILES['profile-image']['size'];
$file_tmp_name = $_FILES['profile-image']['tmp_name'];
//Determine filetype
switch ($_FILES['profile-image']['type']) {
case 'image/jpeg': $ext = "jpg"; break;
case 'image/png': $ext = "png"; break;
default: $ext = ''; break;
}
if ($ext) {
//Check filesize
if ($file_size < 500000) {
//Process file - clean up filename and move to safe location
$n = "$file_name";
$n = ereg_replace("[^A-Za-z0-9.]", "", $n);
$n = strtolower($n);
$n = "avatars/$n";
move_uploaded_file($file_tmp_name, $n);
} else {
$bad_message = "Please ensure your chosen file is less than 5MB.";
}
} else {
$bad_message = "Please ensure your image is of filetype .jpg or.png.";
}
}
$query = "INSERT INTO users (image) VALUES ('$n')";
mysql_query($query) or die("Insert failed. " . mysql_error() . "<br />" . $query);
php
image-processing
image-resizing
image-upload
Alex Ryans
sumber
sumber
upload_max_filesize
inphp.ini
, pertama-tama apakah mungkin untuk mengunggah file dengan ukuran lebih dariupload_max_filesize
?. Apakah ada kemungkinan untuk mengubah ukuran gambar dengan ukuran lebih dariupload_max_filesize
? tanpa mengubahupload_max_filesize
diphp.ini
Jawaban:
Anda perlu menggunakan fungsi ImageMagick atau GD PHP untuk bekerja dengan gambar.
Dengan GD, misalnya, sesederhana ...
function resize_image($file, $w, $h, $crop=FALSE) { list($width, $height) = getimagesize($file); $r = $width / $height; if ($crop) { if ($width > $height) { $width = ceil($width-($width*abs($r-$w/$h))); } else { $height = ceil($height-($height*abs($r-$w/$h))); } $newwidth = $w; $newheight = $h; } else { if ($w/$h > $r) { $newwidth = $h*$r; $newheight = $h; } else { $newheight = $w/$r; $newwidth = $w; } } $src = imagecreatefromjpeg($file); $dst = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); return $dst; }
Dan Anda bisa memanggil fungsi ini, seperti ...
$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
Dari pengalaman pribadi, pengambilan sampel ulang gambar GD juga secara dramatis mengurangi ukuran file, terutama saat pengambilan sampel ulang gambar kamera digital mentah.
sumber
BLOB
s? Saya akan merekomendasikan untuk menyimpan gambar dalam sistem file dan memasukkan referensi ke dalam database Anda. Saya juga merekomendasikan membaca dokumentasi GD (atau ImageMagick) lengkap untuk melihat opsi lain apa yang Anda miliki.abs()
, suka,ceil($width-($width*abs($r-$w/$h)))
dan sama pada bagian ketinggian. Ini diperlukan untuk beberapa kasus.http://wallpapercave.com/wp/wc1701171.jpg
menjadi 400x128 (spanduk) membuat gambar hitam; Saya tidak tahu mengapa itu melakukan itu.imagejpeg($dst, $file);
setelahimagecopyresampled($dst,...
baris. Ubah$file
jika Anda tidak ingin menimpa yang asli.Sumber daya ini(tautan rusak) juga patut dipertimbangkan - beberapa kode yang sangat rapi yang menggunakan GD. Namun, saya memodifikasi potongan kode terakhir mereka untuk membuat fungsi ini yang memenuhi persyaratan OP ...function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) { $target_dir = "your-uploaded-images-folder/"; $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]); $image = new SimpleImage(); $image->load($_FILES[$html_element_name]['tmp_name']); $image->resize($new_img_width, $new_img_height); $image->save($target_file); return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user }
Anda juga perlu memasukkan file PHP ini ...
<?php /* * File: SimpleImage.php * Author: Simon Jarvis * Copyright: 2006 Simon Jarvis * Date: 08/11/06 * Link: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: * http://www.gnu.org/licenses/gpl.html * */ class SimpleImage { var $image; var $image_type; function load($filename) { $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filename); } elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename); } elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename); } } function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } function output($image_type=IMAGETYPE_JPEG) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); } } function getWidth() { return imagesx($this->image); } function getHeight() { return imagesy($this->image); } function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } function scale($scale) { $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } } ?>
sumber
Fungsi PHP Penggunaan Sederhana ( imagescale ):
Sintaksis:
Contoh:
Langkah: 1 Baca file
$image_name = 'path_of_Image/Name_of_Image.jpg|png';
Langkah: 2: Muat File Gambar
$image = imagecreatefromjpeg($image_name); // For JPEG //or $image = imagecreatefrompng($image_name); // For PNG
Langkah: 3: Life-saver kami hadir di '_' | Skala gambar
$imgResized = imagescale($image , 500, 400); // width=500 and height = 400 // $imgResized is our final product
Catatan: imagescale akan berfungsi untuk (PHP 5> = 5.5.0, PHP 7)
Sumber: Klik untuk Baca lebih lanjut
sumber
Jika Anda tidak peduli dengan rasio aspek (yaitu Anda ingin memaksa gambar ke dimensi tertentu), berikut adalah jawaban yang disederhanakan
// for jpg function resize_imagejpg($file, $w, $h) { list($width, $height) = getimagesize($file); $src = imagecreatefromjpeg($file); $dst = imagecreatetruecolor($w, $h); imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height); return $dst; } // for png function resize_imagepng($file, $w, $h) { list($width, $height) = getimagesize($file); $src = imagecreatefrompng($file); $dst = imagecreatetruecolor($w, $h); imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height); return $dst; } // for gif function resize_imagegif($file, $w, $h) { list($width, $height) = getimagesize($file); $src = imagecreatefromgif($file); $dst = imagecreatetruecolor($w, $h); imagecopyresampled($dst, $src, 0, 0, 0, 0, $w, $h, $width, $height); return $dst; }
Sekarang mari kita tangani bagian unggahan. Langkah pertama, unggah file ke direktori yang Anda inginkan. Kemudian panggil salah satu fungsi di atas berdasarkan jenis file (jpg, png atau gif) dan berikan jalur absolut dari file yang Anda unggah seperti di bawah ini:
// jpg change the dimension 750, 450 to your desired values $img = resize_imagejpg('path/image.jpg', 750, 450);
Nilai yang dikembalikan
$img
adalah objek sumber daya. Kami dapat menyimpan ke lokasi baru atau menimpa yang asli seperti di bawah ini:// again for jpg imagejpeg($img, 'path/newimage.jpg');
Semoga ini bisa membantu seseorang. Periksa tautan ini untuk mengetahui lebih lanjut tentang mengubah ukuran Imagick :: resizeImage dan imagejpeg ()
sumber
upload_max_filesize
inphp.ini
, pertama-tama Anda tidak dapat mengunggah file dengan ukuran lebih dariupload_max_filesize
. Apakah ada kesempatan untuk mengubah ukuran gambar ukuran lebih dariupload_max_filesize
tanpa mengubahupload_max_filesize
diphp.ini
Saya berharap ini akan berhasil untuk Anda.
/** * Image re-size * @param int $width * @param int $height */ function ImageResize($width, $height, $img_name) { /* Get original file size */ list($w, $h) = getimagesize($_FILES['logo_image']['tmp_name']); /*$ratio = $w / $h; $size = $width; $width = $height = min($size, max($w, $h)); if ($ratio < 1) { $width = $height * $ratio; } else { $height = $width / $ratio; }*/ /* Calculate new image size */ $ratio = max($width/$w, $height/$h); $h = ceil($height / $ratio); $x = ($w - $width / $ratio) / 2; $w = ceil($width / $ratio); /* set new file name */ $path = $img_name; /* Save image */ if($_FILES['logo_image']['type']=='image/jpeg') { /* Get binary data from image */ $imgString = file_get_contents($_FILES['logo_image']['tmp_name']); /* create image from string */ $image = imagecreatefromstring($imgString); $tmp = imagecreatetruecolor($width, $height); imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h); imagejpeg($tmp, $path, 100); } else if($_FILES['logo_image']['type']=='image/png') { $image = imagecreatefrompng($_FILES['logo_image']['tmp_name']); $tmp = imagecreatetruecolor($width,$height); imagealphablending($tmp, false); imagesavealpha($tmp, true); imagecopyresampled($tmp, $image,0,0,$x,0,$width,$height,$w, $h); imagepng($tmp, $path, 0); } else if($_FILES['logo_image']['type']=='image/gif') { $image = imagecreatefromgif($_FILES['logo_image']['tmp_name']); $tmp = imagecreatetruecolor($width,$height); $transparent = imagecolorallocatealpha($tmp, 0, 0, 0, 127); imagefill($tmp, 0, 0, $transparent); imagealphablending($tmp, true); imagecopyresampled($tmp, $image,0,0,0,0,$width,$height,$w, $h); imagegif($tmp, $path); } else { return false; } return true; imagedestroy($image); imagedestroy($tmp); }
sumber
Saya membuat perpustakaan yang mudah digunakan untuk mengubah ukuran gambar. Itu dapat ditemukan di sini di Github .
Contoh bagaimana menggunakan perpustakaan:
// Include PHP Image Magician library require_once('php_image_magician.php'); // Open JPG image $magicianObj = new imageLib('racecar.jpg'); // Resize to best fit then crop (check out the other options) $magicianObj -> resizeImage(100, 200, 'crop'); // Save resized image as a PNG (or jpg, bmp, etc) $magicianObj -> saveImage('racecar_small.png');
Fitur lainnya, jika Anda membutuhkannya, adalah:
sumber
( PENTING : Dalam kasus animasi (webp animasi atau gif) yang diubah ukurannya, hasilnya tidak akan berupa animasi, tetapi gambar diubah ukurannya dari bingkai pertama! (Animasi asli tetap utuh ...)
Saya membuat ini ke proyek php 7.2 saya (contoh imagebmp sure (PHP 7> = 7.2.0): php / manual / function.imagebmp ) tentang techfry.com/php-tutorial , dengan GD2, (jadi tidak ada perpustakaan pihak ketiga) dan sangat mirip dengan jawaban Nico Bistolfi, tetapi bekerja dengan kelima mimetype gambar dasar ( png, jpeg, webp, bmp dan gif ), membuat file baru yang diubah ukurannya, tanpa memodifikasi yang asli, dan semua barang dalam satu fungsi dan siap digunakan (salin dan tempel ke proyek Anda). (Anda dapat mengatur ekstensi dari file baru dengan parameter kelima, atau biarkan saja, jika Anda ingin mempertahankan orignal):
function createResizedImage( string $imagePath = '', string $newPath = '', int $newWidth = 0, int $newHeight = 0, string $outExt = 'DEFAULT' ) : ?string { if (!$newPath or !file_exists ($imagePath)) { return null; } $types = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_BMP, IMAGETYPE_WEBP]; $type = exif_imagetype ($imagePath); if (!in_array ($type, $types)) { return null; } list ($width, $height) = getimagesize ($imagePath); $outBool = in_array ($outExt, ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']); switch ($type) { case IMAGETYPE_JPEG: $image = imagecreatefromjpeg ($imagePath); if (!$outBool) $outExt = 'jpg'; break; case IMAGETYPE_PNG: $image = imagecreatefrompng ($imagePath); if (!$outBool) $outExt = 'png'; break; case IMAGETYPE_GIF: $image = imagecreatefromgif ($imagePath); if (!$outBool) $outExt = 'gif'; break; case IMAGETYPE_BMP: $image = imagecreatefrombmp ($imagePath); if (!$outBool) $outExt = 'bmp'; break; case IMAGETYPE_WEBP: $image = imagecreatefromwebp ($imagePath); if (!$outBool) $outExt = 'webp'; } $newImage = imagecreatetruecolor ($newWidth, $newHeight); //TRANSPARENT BACKGROUND $color = imagecolorallocatealpha ($newImage, 0, 0, 0, 127); //fill transparent back imagefill ($newImage, 0, 0, $color); imagesavealpha ($newImage, true); //ROUTINE imagecopyresampled ($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); // Rotate image on iOS if(function_exists('exif_read_data') && $exif = exif_read_data($imagePath, 'IFD0')) { if(isset($exif['Orientation']) && isset($exif['Make']) && !empty($exif['Orientation']) && preg_match('/(apple|ios|iphone)/i', $exif['Make'])) { switch($exif['Orientation']) { case 8: if ($width > $height) $newImage = imagerotate($newImage,90,0); break; case 3: $newImage = imagerotate($newImage,180,0); break; case 6: $newImage = imagerotate($newImage,-90,0); break; } } } switch (true) { case in_array ($outExt, ['jpg', 'jpeg']): $success = imagejpeg ($newImage, $newPath); break; case $outExt === 'png': $success = imagepng ($newImage, $newPath); break; case $outExt === 'gif': $success = imagegif ($newImage, $newPath); break; case $outExt === 'bmp': $success = imagebmp ($newImage, $newPath); break; case $outExt === 'webp': $success = imagewebp ($newImage, $newPath); } if (!$success) { return null; } return $newPath; }
sumber
.cr2, .dng, .nef
dan sejenisnya)? GD2 tidak memiliki dukungan apa pun dan setelah banyak perjuangan, saya dapat mengatur ImageMagick. Tapi, gagal dengan kesalahan waktu koneksi habis saat membaca file. Dan, tidak ada catatan kesalahan juga ..Ini adalah versi tambahan dari jawaban yang diberikan @Ian Atkin '. Saya menemukan itu bekerja dengan sangat baik. Untuk gambar yang lebih besar :). Anda sebenarnya bisa memperbesar gambar yang lebih kecil jika Anda tidak hati-hati. Perubahan: - Mendukung file jpg, jpeg, png, gif, bmp - Mempertahankan transparansi untuk .png dan .gif - Memeriksa ulang apakah ukuran aslinya belum lebih kecil - Mengganti gambar yang diberikan secara langsung (Ini yang saya butuhkan)
Jadi begini. Nilai default dari fungsi tersebut adalah "aturan emas"
function resize_image($file, $w = 1200, $h = 741, $crop = false) { try { $ext = pathinfo(storage_path() . $file, PATHINFO_EXTENSION); list($width, $height) = getimagesize($file); // if the image is smaller we dont resize if ($w > $width && $h > $height) { return true; } $r = $width / $height; if ($crop) { if ($width > $height) { $width = ceil($width - ($width * abs($r - $w / $h))); } else { $height = ceil($height - ($height * abs($r - $w / $h))); } $newwidth = $w; $newheight = $h; } else { if ($w / $h > $r) { $newwidth = $h * $r; $newheight = $h; } else { $newheight = $w / $r; $newwidth = $w; } } $dst = imagecreatetruecolor($newwidth, $newheight); switch ($ext) { case 'jpg': case 'jpeg': $src = imagecreatefromjpeg($file); break; case 'png': $src = imagecreatefrompng($file); imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127)); imagealphablending($dst, false); imagesavealpha($dst, true); break; case 'gif': $src = imagecreatefromgif($file); imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127)); imagealphablending($dst, false); imagesavealpha($dst, true); break; case 'bmp': $src = imagecreatefrombmp($file); break; default: throw new Exception('Unsupported image extension found: ' . $ext); break; } $result = imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); switch ($ext) { case 'bmp': imagewbmp($dst, $file); break; case 'gif': imagegif($dst, $file); break; case 'jpg': case 'jpeg': imagejpeg($dst, $file); break; case 'png': imagepng($dst, $file); break; } return true; } catch (Exception $err) { // LOG THE ERROR HERE return false; } }
sumber
$w === $width && $h === $height
. Pikirkan tentang itu. Harus>=
dan>=
perbandingan. @DanielKue ZF:
<?php class FkuController extends Zend_Controller_Action { var $image; var $image_type; public function store_uploaded_image($html_element_name, $new_img_width, $new_img_height) { $target_dir = APPLICATION_PATH . "/../public/1/"; $target_file = $target_dir . basename($_FILES[$html_element_name]["name"]); //$image = new SimpleImage(); $this->load($_FILES[$html_element_name]['tmp_name']); $this->resize($new_img_width, $new_img_height); $this->save($target_file); return $target_file; //return name of saved file in case you want to store it in you database or show confirmation message to user public function load($filename) { $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filename); } elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename); } elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename); } } public function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } public function output($image_type=IMAGETYPE_JPEG) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); } } public function getWidth() { return imagesx($this->image); } public function getHeight() { return imagesy($this->image); } public function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } public function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } public function scale($scale) { $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } public function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } public function savepicAction() { ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $this->_response->setHeader('Access-Control-Allow-Origin', '*'); $this->db = Application_Model_Db::db_load(); $ouser = $_POST['ousername']; $fdata = 'empty'; if (isset($_FILES['picture']) && $_FILES['picture']['size'] > 0) { $file_size = $_FILES['picture']['size']; $tmpName = $_FILES['picture']['tmp_name']; //Determine filetype switch ($_FILES['picture']['type']) { case 'image/jpeg': $ext = "jpg"; break; case 'image/png': $ext = "png"; break; case 'image/jpg': $ext = "jpg"; break; case 'image/bmp': $ext = "bmp"; break; case 'image/gif': $ext = "gif"; break; default: $ext = ''; break; } if($ext) { //if($file_size<400000) { $img = $this->store_uploaded_image('picture', 90,82); //$fp = fopen($tmpName, 'r'); $fp = fopen($img, 'r'); $fdata = fread($fp, filesize($tmpName)); $fdata = base64_encode($fdata); fclose($fp); //} } } if($fdata=='empty'){ } else { $this->db->update('users', array( 'picture' => $fdata, ), array('username=?' => $ouser )); } }
sumber
Saya menemukan cara matematis untuk menyelesaikan pekerjaan ini
Repo Github - https://github.com/gayanSandamal/easy-php-image-resizer
Contoh langsung - https://plugins.nayague.com/easy-php-image-resizer/
<?php //path for the image $source_url = '2018-04-01-1522613288.PNG'; //separate the file name and the extention $source_url_parts = pathinfo($source_url); $filename = $source_url_parts['filename']; $extension = $source_url_parts['extension']; //define the quality from 1 to 100 $quality = 10; //detect the width and the height of original image list($width, $height) = getimagesize($source_url); $width; $height; //define any width that you want as the output. mine is 200px. $after_width = 200; //resize only when the original image is larger than expected with. //this helps you to avoid from unwanted resizing. if ($width > $after_width) { //get the reduced width $reduced_width = ($width - $after_width); //now convert the reduced width to a percentage and round it to 2 decimal places $reduced_radio = round(($reduced_width / $width) * 100, 2); //ALL GOOD! let's reduce the same percentage from the height and round it to 2 decimal places $reduced_height = round(($height / 100) * $reduced_radio, 2); //reduce the calculated height from the original height $after_height = $height - $reduced_height; //Now detect the file extension //if the file extension is 'jpg', 'jpeg', 'JPG' or 'JPEG' if ($extension == 'jpg' || $extension == 'jpeg' || $extension == 'JPG' || $extension == 'JPEG') { //then return the image as a jpeg image for the next step $img = imagecreatefromjpeg($source_url); } elseif ($extension == 'png' || $extension == 'PNG') { //then return the image as a png image for the next step $img = imagecreatefrompng($source_url); } else { //show an error message if the file extension is not available echo 'image extension is not supporting'; } //HERE YOU GO :) //Let's do the resize thing //imagescale([returned image], [width of the resized image], [height of the resized image], [quality of the resized image]); $imgResized = imagescale($img, $after_width, $after_height, $quality); //now save the resized image with a suffix called "-resized" and with its extension. imagejpeg($imgResized, $filename . '-resized.'.$extension); //Finally frees any memory associated with image //**NOTE THAT THIS WONT DELETE THE IMAGE imagedestroy($img); imagedestroy($imgResized); } ?>
sumber
Anda dapat mencoba library PHP TinyPNG. Menggunakan perpustakaan ini gambar Anda dioptimalkan secara otomatis selama proses pengubahan ukuran. Yang Anda perlukan untuk menginstal perpustakaan dan mendapatkan kunci API dari https://tinypng.com/developers . Untuk menginstal perpustakaan, jalankan perintah di bawah ini.
composer require tinify/tinify
Setelah itu, kodenya adalah sebagai berikut.
require_once("vendor/autoload.php"); \Tinify\setKey("YOUR_API_KEY"); $source = \Tinify\fromFile("large.jpg"); //image to be resize $resized = $source->resize(array( "method" => "fit", "width" => 150, "height" => 100 )); $resized->toFile("thumbnail.jpg"); //resized image
Saya memiliki sebuah blog yang ditulis dengan topik yang sama http://artisansweb.net/resize-image-php-using-tinypng
sumber
Saya akan menyarankan cara mudah:
function resize($file, $width, $height) { switch(pathinfo($file)['extension']) { case "png": return imagepng(imagescale(imagecreatefrompng($file), $width, $height), $file); case "gif": return imagegif(imagescale(imagecreatefromgif($file), $width, $height), $file); default : return imagejpeg(imagescale(imagecreatefromjpeg($file), $width, $height), $file); } }
sumber
private function getTempImage($url, $tempName){ $tempPath = 'tempFilePath' . $tempName . '.png'; $source_image = imagecreatefrompng($url); // check type depending on your necessities. $source_imagex = imagesx($source_image); $source_imagey = imagesy($source_image); $dest_imagex = 861; // My default value $dest_imagey = 96; // My default value $dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey); imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey); imagejpeg($dest_image, $tempPath, 100); return $tempPath;
}
Ini adalah solusi yang disesuaikan berdasarkan penjelasan hebat ini . Orang ini membuat penjelasan selangkah demi selangkah. Semoga semua menikmatinya.
sumber