JavaScript 使用基于 64 位编码的代码减少图像的大小和质量 [英] JavaScript reduce the size and quality of image with based64 encoded code

查看:27
本文介绍了JavaScript 使用基于 64 位编码的代码减少图像的大小和质量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张图片的 based64 编码代码.现在我想减小图像的大小和质量.如何在 JavaScript 或 jQuery 中执行此操作?

这里解决的是工作代码:Index.php这是对我有用的javascript代码

<头><title>JavaScript 图像调整大小</title><meta http-equiv="content-type" content="text/html; charset=UTF-8"><风格>身体 {字体大小:16px;字体系列:Arial;}</风格><script type="text/javascript">函数_resize(img, maxWidth, maxHeight){无功比 = 1;var canvas = document.createElement("canvas");canvas.style.display="none";document.body.appendChild(canvas);var canvasCopy = document.createElement("canvas");canvasCopy.style.display="none";document.body.appendChild(canvasCopy);var ctx = canvas.getContext("2d");var copyContext = canvasCopy.getContext("2d");if(img.width > maxWidth)ratio = maxWidth/img.width;否则 if(img.height > maxHeight)ratio = maxHeight/img.height;canvasCopy.width = img.width;canvasCopy.height = img.height;尝试 {copyContext.drawImage(img, 0, 0);}赶上(e){document.getElementById('loader').style.display="none";alert("出现问题 - 请重新上传您的图片");返回假;}canvas.width = img.width * 比例;canvas.height = img.height * 比例;//要改变的行//ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);//您使用的方法签名用于切片ctx.drawImage(canvasCopy, 0, 0, canvas.width, canvas.height);var dataURL = canvas.toDataURL("image/png");document.body.removeChild(canvas);document.body.removeChild(canvasCopy);return dataURL.replace(/^data:image/(png|jpg);base64,/, "");};函数调整大小(){var photo = document.getElementById("photo");如果(照片.文件!=未定义){var loader = document.getElementById("loader");loader.style.display = "内联";var file = photo.files[0];document.getElementById("orig").value = file.fileSize;var preview = document.getElementById("preview");var r = new FileReader();r.onload = (function(previewImage) {返回函数(e){无功maxx = 500;无功最大值 = 500;previewImage.src = e.target.result;var k = _resize(previewImage, maxx, maxy);如果(k!=假){document.getElementById('base64').value= k;document.getElementById('上传').submit();} 别的 {alert('问题 - 请尝试重新上传');}};})(预览);r.readAsDataURL(文件);} 别的 {alert("您的浏览器似乎不支持调整大小");}返回假;}<身体><div align="center"><h2>图像调整大小演示</h2><input type="file" name="photo" id="photo"><br><br><input type="button" onClick="resize();"值=调整大小"><img src="loader.gif" id="loader"/><img src="" alt="图片预览" id="预览"><form name="upload" id="upload" method='post' action='show.php'><textarea name="base64" id="base64" rows='10' cols='90'></textarea><input type="hidden" id="orig" name="orig" value=""/></表单>

Show.php 文件

<头><title>JavaScript 文件上传</title><meta http-equiv="content-type" content="text/html; charset=UTF-8"><风格>身体 {字体大小:16px;字体系列:Arial;}#预览 {显示:无;}#base64 {显示:无;}</风格><身体><?php$base64size = strlen($_POST['base64']);$f = base64_decode($_POST['base64']);$name = microtime(true).".png";file_put_contents("./$name", $f);#header("内容类型:图片/png");#header("Content-Disposition: 附件;文件名="shrunk.png"");#echo $f;#死();?><h2>压缩文件</h2><p>原始文件是:<?=$_POST['orig'];?>字节

<p>传输的大小是:<?=$base64size;?>字节(由于 base64)</p><p>新文件是:<?=filesize("./$name");?>字节

<p><img src="<?=$name;?>"/></p>

解决方案

您可以使用画布,将图像放入其中,缩放并使用新的 base64 代码获取图像 src.

这是执行此操作的函数,它返回 promise 对象,因为需要先加载(缓存)图像,然后再从中绘制画布并获取其编码的 src.

function resizeBase64Img(base64, width, height) {var canvas = document.createElement("canvas");canvas.width = 宽度;canvas.height = 高度;var context = canvas.getContext("2d");var deferred = $.Deferred();$("").attr("src", "data:image/gif;base64," + base64).load(function() {context.scale(width/this.width, height/this.height);context.drawImage(this, 0, 0);deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));});返回 deferred.promise();}

可以这样使用:

resizeBase64Img(oldBase64, 100, 100).then(function(newImg){$("body").append(newImg);});

这里是 jsfiddle

I have the based64 encoded code of an image. Now I want to reduce the size and quality of the image. How can I do this in JavaScript or jQuery?

Resolve here is the working code : Index.php Here is javascript code which worked form me

<html>
<head>
<title>JavaScript Image Resize</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
body {
    font-size: 16px;
    font-family: Arial;
}

</style>
<script type="text/javascript">
function _resize(img, maxWidth, maxHeight) 
{
    var ratio = 1;
    var canvas = document.createElement("canvas");
    canvas.style.display="none";
    document.body.appendChild(canvas);

    var canvasCopy = document.createElement("canvas");
    canvasCopy.style.display="none";
    document.body.appendChild(canvasCopy);

    var ctx = canvas.getContext("2d");
    var copyContext = canvasCopy.getContext("2d");

        if(img.width > maxWidth)
                ratio = maxWidth / img.width;
        else if(img.height > maxHeight)
                ratio = maxHeight / img.height;

        canvasCopy.width = img.width;
        canvasCopy.height = img.height;
try {
        copyContext.drawImage(img, 0, 0);
} catch (e) { 
    document.getElementById('loader').style.display="none";
    alert("There was a problem - please reupload your image");
    return false;
}
        canvas.width = img.width * ratio;
        canvas.height = img.height * ratio;
        // the line to change
        //ctx.drawImage(canvasCopy, 0, 0, canvasCopy.width, canvasCopy.height, 0, 0, canvas.width, canvas.height);
        // the method signature you are using is for slicing
        ctx.drawImage(canvasCopy, 0, 0, canvas.width, canvas.height);
        var dataURL = canvas.toDataURL("image/png");
        document.body.removeChild(canvas);
        document.body.removeChild(canvasCopy);

        return dataURL.replace(/^data:image/(png|jpg);base64,/, "");


};

function resize() { 
    var photo = document.getElementById("photo");

    if(photo.files!=undefined){ 
        var loader = document.getElementById("loader");
        loader.style.display = "inline";
        var file  = photo.files[0];
        document.getElementById("orig").value = file.fileSize;
        var preview = document.getElementById("preview");
        var r = new FileReader();
        r.onload = (function(previewImage) { 
            return function(e) { 
                var maxx = 500;
                var maxy = 500;
                previewImage.src = e.target.result; 
                var k = _resize(previewImage, maxx, maxy);
                if(k!=false) { 
                document.getElementById('base64').value= k;
                document.getElementById('upload').submit();
                } else {
                alert('problem - please attempt to upload again');
                }
            }; 
        })(preview);
        r.readAsDataURL(file);
    } else {
        alert("Seems your browser doesn't support resizing");
    }
    return false;
}

</script>
</head>
<body>

<div align="center">
<h2>Image Resize Demo</h2>

    <input type="file" name="photo" id="photo">
    <br> 
    <br>    
    <input type="button" onClick="resize();" value="Resize">
    <img src="loader.gif" id="loader" />
    <img src="" alt="Image preview" id="preview">
   <form name="upload" id="upload" method='post' action='show.php'>
        <textarea name="base64" id="base64" rows='10' cols='90'></textarea>
        <input type="hidden" id="orig" name="orig" value=""/>
   </form>
</div>

</body>
</html>

Show.php file

<html>
<head>
<title>JavaScript file upload</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<style>
body {
    font-size: 16px;
    font-family: Arial;
}
#preview {
    display:none;
}
#base64 {
    display:none;
}
</style>
</head>
<body>
<?php
$base64size = strlen($_POST['base64']);
$f = base64_decode($_POST['base64']);
$name = microtime(true).".png";
file_put_contents("./$name", $f);
#header("Content-type: image/png");
#header("Content-Disposition: attachment; filename="shrunk.png"");
#echo $f;
#die();
?>
<h2>Shrunk file</h2>
<p>Original file was: <?=$_POST['orig'];?> bytes</p>
<p>Transmitted size was: <?=$base64size;?> bytes (due to base64)</p>
<p>New file is: <?=filesize("./$name");?> bytes</p>
<p><img src="<?=$name;?>"/></p>
</body>
</html>

解决方案

You can use canvas, put image into it, scale it and get image src with new base64 code.

Here's the function doing that, it returns promise object, as image needs to be loaded (cached) first before drawing canvas out of it and getting its encoded src.

function resizeBase64Img(base64, width, height) {
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    var context = canvas.getContext("2d");
    var deferred = $.Deferred();
    $("<img/>").attr("src", "data:image/gif;base64," + base64).load(function() {
        context.scale(width/this.width,  height/this.height);
        context.drawImage(this, 0, 0); 
        deferred.resolve($("<img/>").attr("src", canvas.toDataURL()));               
    });
    return deferred.promise();    
}

Can be used like this:

resizeBase64Img(oldBase64, 100, 100).then(function(newImg){
    $("body").append(newImg);
});

here's the jsfiddle

这篇关于JavaScript 使用基于 64 位编码的代码减少图像的大小和质量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆