简体   繁体   中英

How to compress and resize image from a Rich Text

I am inserting image in using this

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);
});

Let say i added a text Hello World and added a image. Now when i take $("#editor").html() it shows something like below

Here is a sample source of a image+text

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

Now here i have both text+image So both on server side and client side i want to resize & compress image

So that no one can insert image > 5MP and also keep a rich text with resize image in my db

This is how you can do it on the server side (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();
    }

As for the JavaScript part you can use a canvas , size the canvas to the dimension that you want, draw your image on it and use the toDataURL method to convert the image to a String

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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