php - 如何在不裁剪 500 x 500 的情况下压缩图像的宽度和高度

标签 php html

使用 php 上传后,我可以将图像裁剪为 500 x 500 像素。但是,问题是如果图像被压缩,图像就会被裁剪。我希望在不裁剪的情况下将完整图像压缩或调整为 500 x 500 的大小。请帮忙。我提供我的代码以供引用。

function resize_image($file, $width, $height) {
    list($w, $h) = getimagesize($file);

    /* calculate new image size with ratio */
    $ratio = max($width/$w, $height/$h);
    $h = ceil($height / $ratio);
    $x = ($w - $width / $ratio) / 2;
    $w = ceil($width / $ratio);

    /* read binary data from image file */
    $imgString = file_get_contents($file);

    /* create image from string */
    $image = imagecreatefromstring($imgString);
    $tmp = imagecreatetruecolor($width, $height);
    imagecopyresampled($tmp, $image,
        0, 0,
        $x, 0,
        $width, $height,
        $w, $h);
    $ext = pathinfo($file, PATHINFO_EXTENSION); 

    //$ext will be gif

    imagejpeg($tmp, $file, 100);
    return $file;

    /* cleanup memory */

    imagedestroy($image);
    imagedestroy($tmp);
}

最佳答案

我认为, echo 中的 HTML img 会有所帮助:

<?php
echo'<img src="url of image" width="your img width" height="your img height">'
?>

关于php - 如何在不裁剪 500 x 500 的情况下压缩图像的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32047256/

相关文章:

javascript - 如何在 CSS 中设置默认颜色?

php - 在 Yii2 中执行原始 SQL 查询?

php - 如何在 Wordpress 中将 Gravatar 设置为背景图片?

javascript - 一页中多种不同类型的模态框

javascript - 段落第一个字的样式

javascript - 将流程图相对于绘制的图表而不是 Canvas 大小居中。

php - 运行一个函数,数据库中存储的时间戳是上周的

php - 如何在创建数据库之前忽略配置文件

php - 如何从远程服务器收集 HTML 源响应?

html - CSS背景不重复,但有一个空白