[英]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.