LoginSignup
1
0

More than 1 year has passed since last update.

画像をリサイズして表示

Last updated at Posted at 2022-03-18

画像をリサイズして表示する流れ

1.画像を読む込む
imagecreatefromjpeg(ファイルパスorURL|false)
画像オブジェクトをファイルパスもしくはURLから作成する。
成功した場合には画像オブジェクト、エラー時にfalseを返す。

2.画像サイズ取得
getimagesize(string $filename, array &$image_info = null): array|false
サポートする任意の形式の画像ファイルの大きさを決定し、 ファイルの型と高さ/幅を表す文字列を返します。
imagejpeg() 画像からJPEGファイル作成

3.リサイズ
imagecopyresized()  画像の一部をコピーしサイズを変更する
位置 (src_x,src_y) の src_image から幅 src_w と高さ src_h の長方形の領域を取り、位置(dst_x、dst_y)の宛先画像の長方形領域の間に配置。

arg name description
dst_image コピー先の画像リンクリソース
src_image コピー元の画像リンクリソース
dst_x コピー先の x 座標
dst_y コピー先の y 座標
src_x コピー元の x 座標
src_y コピー元の y 座標
dst_w コピー先の幅
dst_h コピー先の高さ
src_w コピー元の幅
src_h コピー元の高さ

4.出力
imagejpeg(ファイル、新しい名前)


リサイズして表示した際に画像の比率が崩れてしまった。→対処

例)入力された画像を比率を変えず縦横300の画像にリサイズする

// 元の画像名を指定してサイズを取得
list($width, $height) = getimagesize($image_before);

//最大幅に縮小拡大
$newwidth = 0; // 新しい横幅
$newheight = 0; // 新しい縦幅
$dst_w = 300; // 最大横幅
$dst_h = 300; // 最大縦幅

$zoom1 = $width / $w;
$zoom2 = $height / $h;
$zoom = ($zoom1 > $zoom2) ? $zoom1 : $zoom2;
$newwidth  = floor($width  / $zoom);
$newheight = floor($height / $zoom);


// サイズを指定して新しい画像のキャンバスを作成
$image = imagecreatetruecolor($dst_w, $dst_h); 

$cutwidth = 0;
$cutheight = 0;
$rewidth = 300;
$reheight = 300;
// サイズを切り取り 300×300にする
if($newwidth>$newheight){
  $zm = $height / $dst_h;
  $rewidth = $width / $zm;
  $cutwidth = ($rewidth - $dst_w)/2 * -1;
}elseif($newheight>$newwidth){
  $zm = $width / $dst_w;
  $reheight = $height / $zm;
  $cutheight = ($reheight - $dst_h)/2 * -1;

// 元の画像から新しい画像を作る準備
$baseImage = imagecreatefromjpeg($image_before);
// 画像のコピーと伸縮
imagecopyresampled($image, $baseImage, $cutwidth, $cutheight, 0, 0, $rewidth, $reheight, $width, $height);
// コピーした画像を出力する
imagejpeg($image,$save_filename);

参考

https://www.delftstack.com/ja/howto/php/image-resizing-in-php/
https://www.sejuku.net/blog/74338
https://qiita.com/redamoon/items/60eb6e899161d516d9f3
https://dev-lib.com/php-image-size-change/

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0