annotorious / annotorious-v1

Project has moved to http://github.com/annotorious/annotorious
https://annotorious.com
MIT License
593 stars 142 forks source link

how to save all selected/annotated part of image on server #207

Open avaiyahardik opened 5 years ago

avaiyahardik commented 5 years ago

Hi,

I want to create small small images as I am annotating any image and want to render all those pieces independently on the web page.

For example, refer attached image which I have annotated with 3 shapes. Now I want to save these 3 shapes independently on the server so that I can serve them independent of an original image. inked1_li

Let me know if this is possible with Annotorious.

Really good work!

wuliupo commented 5 years ago

@avaiyahardik

It is a solution for you. Just create a canvas and export it as an image.

let image = document.getElementById('YOUR_IMG_ID');
let { naturalWidth, naturalHeight } = image;
let canvas = document.createElement('canvas');
canvas.width = image.naturalWidth;  // use the original size
canvas.height = image.naturalHeight;

let context = canvas.getContext('2d');
context.drawImage(image, 0, 0, naturalWidth, naturalHeight);

anno.getAnnotations().forEach(item => {
    let { x, y, width, height } = item.shapes[0].geometry;
    context.shadowOffsetX = 3;
    context.shadowOffsetY = 3;
    context.shadowBlur = 3;
    context.shadowColor = 'rgba(255, 255, 255, 0.5)';
    context.strokeStyle = '#131313';
    context.lineWidth = 3;
    context.globalCompositeOperation = 'source-in'; // it is key point
    context.fillRect(x, y, width, height); // fillRect or strokeRect
}

let base64 = canvas.toDataURL('image/jpeg', 0.7);
base64 = base64.replace(/^data:image\/\w+;base64,/, '');
base64 = atob(base64);
let count = base64.length;
let u8arr = new Uint8Array(count);
while (count--) {
    u8arr[count] = base64.charCodeAt(count);
}
let file = new File([u8arr], 'output.jpg', { type: 'jpeg' });

let form = new FormData();
form.append('file', file);

axios.post('/YOUR_API_URL', form);