Answer the question
In order to leave comments, you need to log in
Compress image size?
Hello. Tell me please. The best way to do this is to make a mini editor for the image (rotation, filters, offset).
And you need to pre-display images in the size of 1024 x AUTO.
So the question is how best to do this?
1) Immediately somehow compress the image to the required size and save this state? And then work with him.
2) Or initially work with the original images, adding a compression ratio to it?
Here is the source code of the program.
renderImage() {
const {
image, canvas, context,
scale, offsetX, offsetY, rotate,
contrast, brightness, balanceColor
} = this;
const canvasSize = canvas.clientWidth;
const centerSize = canvasSize / 2;
canvas.width = canvasSize;
canvas.height = canvasSize;
// Clear canvas
context.clearRect(0, 0, canvasSize, canvasSize);
context.save();
// Фильтры - яркость и контрасность
let filter = '';
filter += ` contrast(${contrast})`;
filter += ` brightness(${brightness})`;
context.filter = filter;
// Вращение изображения
let offsetRotate = 0;
if (rotate) {
offsetRotate = centerSize;
context.translate(offsetRotate, offsetRotate);
context.rotate(rotate * Math.PI / 180);
}
// Маштабирование
const scaleKoef = (10 + scale) / 10;
const scaleSize = canvasSize / scaleKoef * Math.sqrt(2);
// Смещение изображения
const offsetXMain = -offsetX * image.width / 100 * scaleKoef;
const offsetYMain = -offsetY * image.height / 100 * scaleKoef;
context.drawImage(
image,
offsetXMain, offsetYMain, scaleSize, scaleSize,
-offsetRotate, -offsetRotate, canvasSize, canvasSize
);
// Делаем картинку черно-белой
const imageData = context.getImageData(0, 0, canvasSize, canvasSize);
const balanceColorKoef = 122.5 + balanceColor * 1.225;
for (let i = 0; i < imageData.data.length; i += 4) {
const red = imageData.data[i];
const green = imageData.data[i + 1];
const blue = imageData.data[i + 2];
const alpha = imageData.data[i + 3];
const isWhite = ((red + green + blue) / 3) > balanceColorKoef || alpha < balanceColorKoef;
const color = isWhite ? 255 : 0;
imageData.data[i] = color;
imageData.data[i + 1] = color;
imageData.data[i + 2] = color;
if (alpha !== 255) imageData.data[i + 3] = 255;
}
context.putImageData(imageData, 0, 0);
// Берем картинку в кружочек и белый фон позади кружочка
context.restore();
context.globalCompositeOperation = 'destination-in';
context.arc(centerSize, centerSize, centerSize, 0, 2 * Math.PI);
context.fill();
context.globalCompositeOperation = 'destination-over';
context.rect(0, 0, canvasSize, canvasSize);
context.fillStyle = 'white';
context.fill();
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question