繁体   English   中英

如何通过RTF压缩图像并调整其大小

[英]How to compress and resize image from a Rich Text

我正在使用此插入图像

var readFileIntoDataUrl = function (fileInfo) {
    var loader = $.Deferred(),
        fReader = new FileReader();
    fReader.onload = function (e) {
        loader.resolve(e.target.result);
    };
    fReader.onerror = loader.reject;
    fReader.onprogress = loader.notify;
    fReader.readAsDataURL(fileInfo);
    return loader.promise();
};


$.when(readFileIntoDataUrl(fileInfo)).done(function (dataUrl) {
        execCommand('insertimage', dataUrl);
}).fail(function (e) {
        options.fileUploadError("file-reader", e);
});

假设我添加了文本Hello World并添加了图像。 现在,当我使用$("#editor").html()它显示如下内容

这是图像+文本的示例来源

Hello World!
img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgA
BAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAA
AQAAAGAAAAABUGFpbnQuTkVUIHYzLjUuOAAA/9sAQwAHBQUGBQQHBgUGCAcHCAoRCwoJCQoVDxAMERgV
[... more base64 data here....]

现在在这里我同时具有text+image因此在服务器端和客户端,我都希望调整图像大小并压缩图像

这样,没有人可以插入图像> 5MP,并且还可以在数据库中保留带有调整大小图像的富文本格式

这是您可以在服务器端(Java)上执行的操作:

    String imageData = "Hello World! img src=\"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoR...";

    //Image data starting point
    int startIndex = imageData.indexOf(";base64,") + ";base64,".length();

    //keep only the image data
    imageData = imageData.substring(startIndex, imageData.length());

    //convert the image data String to a byte[]
    byte[] dta = DatatypeConverter.parseBase64Binary(imageData);
    try (InputStream in = new ByteArrayInputStream(dta);) {
        BufferedImage fullSize = ImageIO.read(in);

        // Create a new image half the size of the original image
        BufferedImage resized = new BufferedImage(fullSize.getWidth() / 2, fullSize.getHeight() / 2, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics2D g2 = (Graphics2D) resized.getGraphics();
        g2.drawImage(fullSize, 0, 0, resized.getWidth(), resized.getHeight(), 0, 0, fullSize.getWidth(), fullSize.getHeight(), null);
        g2.dispose();
    } catch (IOException e) {
        e.printStackTrace();
    }

至于JavaScript部分,您可以使用canvas ,将画布的大小调整为所需的尺寸,在其上绘制图像,然后使用toDataURL方法将图像转换为String

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM