JSP/javascript jQuery

[javascript] 두 이미지를 비교하기

도미노& 2021. 10. 13. 14:06

2020년 10가지 JavaScript 이미지 조작 라이브러리
https://ichi.pro/ko/2020-nyeon-10-gaji-javascript-imiji-jojag-laibeuleoli-26937466213807

 

구글 검색 키워드 : javascript 이미지 비교

* https://www.it-gundan.com/ko/javascript/javascript%EC%97%90%EC%84%9C-%EB%91%90-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EB%B9%84%EA%B5%90/972817711/

https://stackoverflow.com/questions/934012/get-image-data-url-in-javascript

 

 

* 아래 코드는 두 이미지를 base64로 변경해서 비교하는 소스로, 완전히 똑같아야만 한다.

<!-- html -->
<input type="file" id="fileImgTest" accept="img/*" required multiple onchange="fnComparison(event);" />

<!-- script -->
function fnComparison(e) {
	var a = new Image();
	var b = new Image();
	
	var sel_files = [];
	
	var files = e.target.files;
	var fileArr = Array.prototype.slice.call(files);
	var index = 0;
	
	fileArr.forEach(function(f) {
		if(!f.type.match("image/.*")) {
			alert("이미지 확장자만 업로드 가능합니다.");
			return;
		}
		if(files.length !== 2) {
			alert("2장을 업로드해야 합니다.");
			return;
		}
		if(files.length === 2) { // 2장만 가능
			sel_files.push(f);
			var reader = new FileReader();
			reader.onload = function(e) {
				if(index === 0) {
					a.src = e.target.result;
				} else if(index === 1) {
					b.src = e.target.result;
				}
				/* image 미리보기
				var html = '<a id=img_id_${index}><img src=${e.target.result} data-file=${f.name} /></a>';
				$('imagePreview').append(html);
				*/
				index++;
			};
			reader.readAsDataURL(f);
		}
	});
	
	var a_base64 = getBase64Image(a);
	var b_base64 = getBase64Image(b);
	if (a_base64 === b_base64) {
		// 같음
		alert("they are identical");
	} else {
		// 다름
		alert("you can probably guess what this means");
	}
}

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

 

이런 js도 있다.

https://github.com/rsmbl/Resemble.js

https://github.com/HuddleEng/PhantomCSS