调整在JavaScript中的Base-64图像,而无需使用帆布 [英] Resize a Base-64 image in JavaScript without using canvas

查看:136
本文介绍了调整在JavaScript中的Base-64图像,而无需使用帆布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来调整在JavaScript中的照片,而无需使用的HTML元素。

I need a way to resize pictures in JavaScript without using an HTML element.

我的移动应用程序的HTML拍摄照片,然后将它们转换为base64字符串。此后我需要调整他们,他们是为了节省存储空间传送到API之前。

My mobile HTML app takes pictures and then converts them to base64 strings. Thereafter I need to resize them before they are sent to the API in order to save storage space.

我在寻找一个不同的,更合适的方式来调整它们的大小,然后用canvas元素。有什么办法?

I'm looking for a different and more suitable way to resize them then using a canvas element. Is there a way?

推荐答案

要避免受到影响的主要HTML的方法是创建一个保持了DOM树的屏幕外的画布。

A way to avoid the main HTML to be affected is to create an off-screen canvas that is kept out of the DOM-tree.

这将提供一个缓冲的位图和原生编译code到EN code中的图像数据。这是直截了当的事:

This will provide a bitmap buffer and native compiled code to encode the image data. It is straight forward to do:

function imageToDataUri(img, width, height) {

    // create an off-screen canvas
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');

    // set its dimension to target size
    canvas.width = width;
    canvas.height = height;

    // draw source image into the off-screen canvas:
    ctx.drawImage(img, 0, 0, width, height);

    // encode image to data-uri with base64 version of compressed image
    return canvas.toDataURL();
}

如果你想产生比PNG(默认)不同的格式只是指定这样的类型:

If you want to produce a different format than PNG (default) just specify the type like this:

return canvas.toDataURL('image/jpeg', quality);  // quality = [0.0, 1.0]

值得说明的是 CORS 限制适用于 toDataURL()

如果您的应用程序只提供连接的base64 $ C $光盘镜像(我以为他们是数据的URI使用Base64的数据?),那么你需要负载的形象第一次:

If your app is giving only base64 encoded images (I assume they are data-uri's with base64 data?) then you need to "load" the image first:

var img = new Image;

img.onload = resizeImage;
img.src = originalDataUriHere;

function resizeImage() {
    var newDataUri = imageToDataUri(this, targetWidth, targetHeight);
    // continue from here...
}

如果源是纯基础-64字符串只需添加一个标头,使之成为数据-URI:

If the source is pure base-64 string simply add a header to it to make it a data-uri:

function base64ToDataUri(base64) {
    return 'data:image/png;base64,' + base64;
}

只需更换同类型的base64字符串重新presents的图像/ PNG 部分(即使它成为一个可选的参数)。

Just replace the image/png part with the type the base64 string represents (ie. make it an optional argument).

这篇关于调整在JavaScript中的Base-64图像,而无需使用帆布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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