javascript - 带水印和调整大小的php图像上传
问题描述
我有以下代码可以将图片上传到我的网站,但是上传的图片看起来很大并且需要时间加载到网站中,我想让它们的尺寸更小,并且我想自己添加水印,
我希望图像显示为 1080X1080 但质量好,我尝试将有限的上传尺寸缩小,但有些用户不知道如何调整照片大小!
$total = count($_FILES['document']['name']);
if($total > 0 ) {
$total = count($_FILES['document']['name']);
if($total<=4)
{
for( $i=0 ; $i < $total ; $i++ ) {
$canUpload = canUpload($_FILES['document'],$i);
if ($canUpload === true){
if (!is_dir($uploadDir)){
umask(0);
mkdir($uploadDir, 0775);
}
$newfile = time().$_FILES['document']['name'][$i];
if($i==0)
$filename = $newfile;
if($i==0)
$filename2 = $newfile;
else
$filename2=$filename2.",".$newfile;
if (file_exists($uploadDir. '/' .$newfile)){
$documentError = 'File already exsist';
} else {
move_uploaded_file($_FILES['document']['tmp_name'][$i], $uploadDir. '/' .$newfile);
}
} else{
$documentError = $canUpload;
}
}
}
else
{
$documentError ="4 images allowed Only!";
}
解决方案
您需要使用 PHP 的ImageMagick或GD函数来处理图像。
以 GD 为例,它就像...
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;
}
你可以调用这个函数,像这样......
$img = resize_image(‘/path/to/some/image.jpg’, 200, 200);
从个人经验来看,GD 的图像重采样确实也大大减小了文件大小,尤其是在重采样原始数码相机图像时。
和水印
PHP手册中的一个很好的例子:
// Load the stamp and the photo to apply the watermark to
$stamp = imagecreatefrompng('stamp.png');
$im = imagecreatefromjpeg('photo.jpeg');
// Set the margins for the stamp and get the height/width of the stamp image
$marge_right = 10;
$marge_bottom = 10;
$sx = imagesx($stamp);
$sy = imagesy($stamp);
// Copy the stamp image onto our photo using the margin offsets and the photo
// width to calculate positioning of the stamp.
imagecopy($im, $stamp, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($stamp), imagesy($stamp));
// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
推荐阅读
- c# - 使用 Newtonsoft 的 PopulateObject 函数时出现 JsonSerializationException
- python - ModuleNotFoundError:没有名为“code.victim”的模块;“代码”不是一个包
- javascript - 导出 PNG 画布所有 div 内容时出错
- java - 从 java admin sdk 连接到 Firestore 模拟器
- sql - 如何对数据组进行排序?
- ansible - Ansible:尝试使用 influxdb_write 时无法在 localhost 上导入所需的 Python 库(influxdb)
- macos-catalina - 在终端上使用 opam 在 mac os catalina 上安装 gmp(frama-c 先决条件)时出错
- installation - 检查 PWA 是否已安装
- javascript - Javascript - 理解递归内部函数 [已解决]
- caching - 缓存位置注意事项