30

私の管理下にない画像が 100,000 枚あります。これらの画像の中には、画像が境界線まで伸びているという点で優れているものもあれば、余分な余白があるものもあります。

空白が多すぎると、ページの見栄えが悪くなり、画面上の画像がすべて異なるサイズに見えることを意味します。

ここで私が何を意味するかを見ることができます:

http://www.fitness-saver.com/uk/shop/mountain-bikes/

私が探していたのは、画像をトリミングして空白を自動的に削除する jQuery メソッドです。

1) 画像ごとに余白の量が異なる 2) 画像の比率が異なる 3) 画像を前処理するのではなく、JavaScript を使用したい。

あなたが助けてくれることを願っています!

編集: これは画像の例です - http://images.productserve.com/preview/3395/128554505.jpg . 画像はさまざまなアフィリエイト サイトからのものであり、間違いなく別のドメインのものであることに注意してください。

4

2 に答える 2

53

画像の空白を分析するには、私が知っている唯一の方法は、その画像を次のようにロードすることですcanvas

var img = new Image(),
    $canvas = $("<canvas>"), // create an offscreen canvas
    canvas = $canvas[0],
    context = canvas.getContext("2d");

img.onload = function () {
   context.drawImage(this, 0, 0); // put the image in the canvas
   $("body").append($canvas);
   removeBlanks(this.width, this.height);
};

// test image
img.src = 'http://images.productserve.com/preview/1302/218680281.jpg';

次に、getImageData()メソッドを使用します。このメソッドは、各ピクセル データ (色) の検査に使用できる ImageData オブジェクトを返します。

var removeBlanks = function (imgWidth, imgHeight) {
    var imageData = context.getImageData(0, 0, canvas.width, canvas.height),
             data = imageData.data,
           getRBG = function(x, y) {
                      return {
                        red:   data[(imgWidth*y + x) * 4],
                        green: data[(imgWidth*y + x) * 4 + 1],
                        blue:  data[(imgWidth*y + x) * 4 + 2]
                      };
                    },
          isWhite = function (rgb) {
                      return rgb.red == 255 && rgb.green == 255 && rgb.blue == 255;
                    },
            scanY = function (fromTop) {
                      var offset = fromTop ? 1 : -1;

                      // loop through each row
                      for(var y = fromTop ? 0 : imgHeight - 1; fromTop ? (y < imgHeight) : (y > -1); y += offset) {

                        // loop through each column
                        for(var x = 0; x < imgWidth; x++) {
                            if (!isWhite(getRBG(x, y))) {
                                return y;                        
                            }      
                        }
                    }
                    return null; // all image is white
                },
            scanX = function (fromLeft) {
                      var offset = fromLeft? 1 : -1;

                      // loop through each column
                      for(var x = fromLeft ? 0 : imgWidth - 1; fromLeft ? (x < imgWidth) : (x > -1); x += offset) {

                        // loop through each row
                        for(var y = 0; y < imgHeight; y++) {
                            if (!isWhite(getRBG(x, y))) {
                                return x;                        
                            }      
                        }
                    }
                    return null; // all image is white
                };


        var cropTop = scanY(true),
            cropBottom = scanY(false),
            cropLeft = scanX(true),
            cropRight = scanX(false);
    // cropTop is the last topmost white row. Above this row all is white
    // cropBottom is the last bottommost white row. Below this row all is white
    // cropLeft is the last leftmost white column.
    // cropRight is the last rightmost white column.
};

率直に言って、私は正当な理由でこのコードをテストできませんでした: 悪名高い " Unable to get image data from canvas because the canvas has been tainted by cross-origin data. " セキュリティ例外に遭遇しました。

これはバグではなく、意図された機能です。仕様から:

toDataURL()、toDataURLHD()、toBlob()、getImageData()、および getImageDataHD() メソッドはフラグをチェックし、クロスオリジン データをリークするのではなく、SecurityError 例外をスローします。

これは、 がdrawImage()外部ドメインからファイルをロードしたときに発生します。これにより、キャンバスのorigin-cleanフラグが false に設定され、それ以上のデータ操作が妨げられます。

同じ問題が発生するのではないかと思いますが、コードは次のとおりです。

これがクライアント側で機能したとしても、パフォーマンスに関してどれほど惨めになるか想像できます。したがって、Jan が言ったように、画像をダウンロードしてサーバー側で前処理できれば、そのほうがよいでしょう。


編集:私のコードが実際に画像をトリミングするかどうかを知りたいと思っていましたが、実際にトリミングされています。 ここに画像の説明を入力

ここで確認できます

前述のように、ドメインの画像に対してのみ機能します。背景が白い独自の画像を選択して、最後の行を変更できます。

// define here an image from your domain
img.src = 'http://localhost/strawberry2.jpg'; 

明らかに、jsFiddle からではなく、ドメインからコードを実行する必要があります。


Edit2:同じ縦横比を維持するためにトリミングして拡大する場合は、これを変更します

var $croppedCanvas = $("<canvas>").attr({ width: cropWidth, height: cropHeight });

// finally crop the guy
$croppedCanvas[0].getContext("2d").drawImage(canvas,
    cropLeft, cropTop, cropWidth, cropHeight,
    0, 0, cropWidth, cropHeight);

var $croppedCanvas = $("<canvas>").attr({ width: imgWidth, height: imgHeight });

// finally crop the guy
$croppedCanvas[0].getContext("2d").drawImage(canvas,
    cropLeft, cropTop, cropWidth, cropHeight,
    0, 0, imgWidth, imgHeight);

Edit3:ブラウザーで画像をトリミングする 1 つの高速な方法は、この優れた記事で説明されているように、 Web Workersを使用してワークロードを並列化することです。

于 2012-08-29T12:58:10.353 に答える
20

によって提供された優れた回答に基づいて、jQuery ライブラリをロードせずにオブジェクトJose Rui Santosだけで動作するように彼のコードを変更しました。image

この関数の戻り値は、画像要素で直接使用されるトリミングされた画像データの URL です。

/*
    Source: http://jsfiddle.net/ruisoftware/ddZfV/7/
    Updated by: Mohammad M. AlBanna
    Website: MBanna.info 
    Facebook: FB.com/MBanna.info
*/

var myImage = new Image();
myImage.crossOrigin = "Anonymous";
myImage.onload = function(){
    var imageData = removeImageBlanks(myImage); //Will return cropped image data
}
myImage.src = "IMAGE SOURCE";



//-----------------------------------------//
function removeImageBlanks(imageObject) {
    imgWidth = imageObject.width;
    imgHeight = imageObject.height;
    var canvas = document.createElement('canvas');
    canvas.setAttribute("width", imgWidth);
    canvas.setAttribute("height", imgHeight);
    var context = canvas.getContext('2d');
    context.drawImage(imageObject, 0, 0);

    var imageData = context.getImageData(0, 0, imgWidth, imgHeight),
        data = imageData.data,
        getRBG = function(x, y) {
            var offset = imgWidth * y + x;
            return {
                red:     data[offset * 4],
                green:   data[offset * 4 + 1],
                blue:    data[offset * 4 + 2],
                opacity: data[offset * 4 + 3]
            };
        },
        isWhite = function (rgb) {
            // many images contain noise, as the white is not a pure #fff white
            return rgb.red > 200 && rgb.green > 200 && rgb.blue > 200;
        },
                scanY = function (fromTop) {
        var offset = fromTop ? 1 : -1;

        // loop through each row
        for(var y = fromTop ? 0 : imgHeight - 1; fromTop ? (y < imgHeight) : (y > -1); y += offset) {

            // loop through each column
            for(var x = 0; x < imgWidth; x++) {
                var rgb = getRBG(x, y);
                if (!isWhite(rgb)) {
                    if (fromTop) {
                        return y;
                    } else {
                        return Math.min(y + 1, imgHeight);
                    }
                }
            }
        }
        return null; // all image is white
    },
    scanX = function (fromLeft) {
        var offset = fromLeft? 1 : -1;

        // loop through each column
        for(var x = fromLeft ? 0 : imgWidth - 1; fromLeft ? (x < imgWidth) : (x > -1); x += offset) {

            // loop through each row
            for(var y = 0; y < imgHeight; y++) {
                var rgb = getRBG(x, y);
                if (!isWhite(rgb)) {
                    if (fromLeft) {
                        return x;
                    } else {
                        return Math.min(x + 1, imgWidth);
                    }
                }      
            }
        }
        return null; // all image is white
    };

    var cropTop = scanY(true),
        cropBottom = scanY(false),
        cropLeft = scanX(true),
        cropRight = scanX(false),
        cropWidth = cropRight - cropLeft,
        cropHeight = cropBottom - cropTop;

    canvas.setAttribute("width", cropWidth);
    canvas.setAttribute("height", cropHeight);
    // finally crop the guy
    canvas.getContext("2d").drawImage(imageObject,
        cropLeft, cropTop, cropWidth, cropHeight,
        0, 0, cropWidth, cropHeight);

    return canvas.toDataURL();
}
于 2015-11-05T23:13:56.437 に答える