新手入门,实现了图片预览和上传,但是不懂压缩,在网上找了一段压缩函数,但是一直套不进去,请前辈指点,如何在现有html、js、php基础上加入压缩,谢谢o(∩_∩)o 。。。代码如下:
php接收:
";
echo "
";
echo "
";
var_dump($_POST);
echo "
";
echo "
";
echo "
";
$dest_folder = "images/";
if(!file_exists($dest_folder)){
if(mkdir($dest_folder)){
}else{
echo"创建文件夹失败
";
}
}
foreach ($_FILES["file"]["error"] as $key => $error ){
if ($error == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["file"]["tmp_name"][$key];
$name = time().$key.$_FILES["file"]["name"][$key];
$uploadfile = $dest_folder.$name;
//$filepath="/images/";
//$filepath=$filepath.$uploadfile;
move_uploaded_file($tmp_name, $uploadfile);
$php_self = $_SERVER['PHP_SELF'];
$php_dir = dirname($php_self);
//$url = 'http://'.$_SERVER['HTTP_HOST'].$php_dir.'/'.$uploadfile;
$arr = array(
'id' => $key,
//'url' => $url
'url' => $name
);
echo json_encode($arr);
}
}
?>
网上找的压缩函数:
// 使用canvas对大图片进行压缩
function compress(img) {
var initSize = img.src.length;
var width = img.width;
var height = img.height;
//如果图片大于四百万像素,计算压缩比并将大小压至400万以下
var ratio;
if ((ratio = width * height / 4000000) > 1) {
ratio = Math.sqrt(ratio);
width /= ratio;
height /= ratio;
} else {
ratio = 1;
}
canvas.width = width;
canvas.height = height;
// 铺底色
ctx.fill;
ctx.fillRect(0, 0, canvas.width, canvas.height);
//如果图片像素大于100万则使用瓦片绘制
var count;
if ((count = width * height / 1000000) > 1) {
count = ~~ (Math.sqrt(count) + 1); //计算要分成多少块瓦片
// 计算每块瓦片的宽和高
var nw = ~~ (width / count);
var nh = ~~ (height / count);
tCanvas.width = nw;
tCanvas.height = nh;
for (var i = 0; i < count; i++) {
for (var j = 0; j < count; j++) {
tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
}
}
} else {
ctx.drawImage(img, 0, 0, width, height);
}
//进行最小压缩
var ndata = canvas.toDataURL('image/jpeg', 0.1);
console.log('压缩前:' + initSize);
console.log('压缩后:' + ndata.length);
console.log('压缩率:' + ~~ (100 * (initSize - ndata.length) / initSize) + "%");
tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
return ndata;
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这也叫压缩……这不就是把图片缩小了嘛。
要上传的话,去学习一下表单的操作,以及 Ajax 你也应该用得上。