如何压缩和调整富文本格式的图像

时间:2015-02-03 17:45:39

标签: java javascript jquery rich-text-editor richtext

我正在使用此

插入图片
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并且还在我的数据库中保留带有调整大小图像的富文本

1 个答案:

答案 0 :(得分:2)

这是你在服务器端(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方法将图像转换为{{ 1}}

相关问题