我有一個類似的問題,實際上發現了一個有用的函數來檢測子採樣,並且只在使用子採樣時使用MegaPixImage
。
在我的情況下,本地文件讀取(iPhone的攝像頭,你的情況),我當<input type="file">
值改變稱爲handleFileSelect
功能(當文件被選中來填充這個輸入即)。在這個函數內部,我調用了一個將圖像數據繪製到畫布的常規populateImage
JS函數。
這裏的handleFileSelect
功能和input
結合:
$("#my_file_input").bind('change', function (event) {
handleFileSelect(event);
});
function handleFileSelect(event) {
var reader,
tmp,
file = event.target.files[0];
try {
reader = new FileReader();
reader.onload = function (e) {
tmp = e.target.result.toString();
// In my case, some image data (from Androids, mostly) didn't contain necessary image data, so I added it in
if (tmp.search("image/jpeg") === -1 && tmp.search("data:base64") !== -1) {
tmp = tmp.replace("data:", "data:image/jpeg;");
}
populateImage(tmp);
};
reader.onerror = function (err) {
// Handle error as you need
};
reader.readAsDataURL(file);
} catch (error) {
// Handle error as you need
}
}
然後,我populateImage
功能(稱爲在上面的reader.onload
功能):
function populateImage(imageURL) {
var tmpImage = new Image();
$(tmpImage).load(function() {
var mpImg, mpImgData;
// If subsampling found, render using MegaPixImage fix, grab image data, and re-populate so we can use non-subsampled image.
// Note: imageCanvas is my canvas element.
if (detectSubsampling(this)) {
mpImg = new MegaPixImage(this);
mpImg.render(imageCanvas, {maxWidth: 94, maxHeight: 125});
mpImgData = imageCanvas.toDataURL("image/jpg");
populateImage(mpImgData);
return;
}
// Insert regular code to draw image to the canvas
// Note: ctx is my canvas element's context
ctx.drawImage(tmpImage, 0, 0, 94, 125); // Or whatever x/y/width/height values you need
});
$(tmpImage).error(function (event) {
// Handle error as you need
});
tmpImage.src = imageURL;
}
最後但並非最不重要的,detectSubsampling
功能。請注意,此方法是從另一個來源找到的,不是我自己的。
function detectSubsampling(img) {
var iw = img.naturalWidth,
ih = img.naturalHeight,
ssCanvas,
ssCTX;
if (iw * ih > 1024 * 1024) { // Subsampling may happen over megapixel image
ssCanvas = document.createElement('canvas');
ssCanvas.width = ssCanvas.height = 1;
ssCTX = ssCanvas.getContext('2d');
ssCTX.drawImage(img, -iw + 1, 0);
// Subsampled image becomes half smaller in rendering size.
// Check alpha channel value to confirm image is covering edge pixel or not.
// If alpha value is 0 image is not covering, hence subsampled.
return ssCTX.getImageData(0, 0, 1, 1).data[3] === 0;
}
return false;
}
這可能比你討價還價的更多,但就像我說的,我遇到類似的問題,這種解決方案被證明在所有瀏覽器/那名支持畫布設備一起使用。
希望它有幫助!
啊謝謝!你回答,然後一些!感謝幫助。 – Chaz 2013-05-10 20:11:51
安東尼,遇到一個小小的死神,我希望你能幫助我。 Im將megapix圖像繪製到188x125的canvas元素中,以便我可以處理它並在canvas元素的另一半上繪製處理後的圖像(兩個圖像均爲94x125並排)。當我來自'if(detectSubsampling ...)條件時,它將調整canvas元素的大小爲94x125,按照mp.Img.render(imageCanvas,{maxWidth:94,maxHeight:125});'。我可以把mpImg放到一個寬度爲圖像寬度兩倍的畫布上嗎?謝謝 – Chaz 2013-05-15 14:25:53
我認爲你可以使'maxWidth'值爲188.我認爲你的畫布是94x125,但是如果你的畫布是188x125,嘗試設置maxWidth到188.在我的項目代碼中,我將maxWidth和maxHeight設置爲我的canvas元素的大小,而不是你指定的一半。希望它可以幫助! – 2013-05-16 18:09:18