2016-04-06 15 views
4

BufferedImageの矩形を抽出したいと思います。BufferedImage:同じデータでサブ画像を抽出する

Javadocは、getSubImage(x、y、w、h)およびgetData(長方形)を提案します。

getDataはすばらしいですが、私はラスターだけは望んでいません。私は、BufferedImageオブジェクトとしてサブイメージをしたいが、私もそれの修正版データ配列を必要とするが、javadocツールは

公共のBufferedImage getSubimage(int型のx、int型のY、W int型、int型H)言う:定義されたサブイメージを返します。指定された矩形領域で囲みます。 返されるBufferedImageは元の画像と同じデータ配列を共有します。

Q:圧縮されたデータ配列でサブ画像を抽出するにはどうすればよいですか?

+1

サブ画像を抽出し、それは別のBufferedImageを行うペイント、あなたの心のコンテンツ – MadProgrammer

+0

に変更し、それがcomputationnaly効率的ですか? –

+0

私は分かりません。シンプルで機能していて、サブイメージのコピーですが、変更されたときに元のイメージには反映されないBufferedImageを提供します。行って、あなたのために何が効果があるかを確認するためにあなた自身の比較のいくつかをしてください – MadProgrammer

答えて

5

は、ここでは「深いを作成するための3つの方法があります「コピーサブイメージ:

// Create an image 
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_4BYTE_ABGR); 

// Fill with static 
new Random().nextBytes(((DataBufferByte) image.getRaster().getDataBuffer()).getData()); 

あなたがgetData(rect)から取得Rasterのすでに深いコピー周辺の画像を作成します。これにはWritableRasterへのキャストが含まれているため、一部のJava実装または将来的には破損する可能性があります。

// Get sub-raster, cast to writable and translate it to 0,0 
WritableRaster data = ((WritableRaster) image.getData(new Rectangle(25, 25, 50, 50))).createWritableTranslatedChild(0, 0); 

// Create new image with data 
BufferedImage subOne = new BufferedImage(image.getColorModel(), data, image.isAlphaPremultiplied(), null); 

を別のオプション、「通常の方法」のサブ画像を作成し、その新しいイメージへのラスタのコピー:あなたは一度だけデータをコピーして、非常に高速である必要があります。

// Get subimage "normal way" 
BufferedImage subimage = image.getSubimage(25, 25, 50, 50); 

// Create empty compatible image 
BufferedImage subTwo = new BufferedImage(image.getColorModel(), image.getRaster().createCompatibleWritableRaster(50, 50), image.isAlphaPremultiplied(), null); 

// Copy data into the new, empty image 
subimage.copyData(subTwo.getRaster()); 

最後に、簡単にルート、ちょうど新しい空の画像の上にサブイメージを描く:まだ、一度だけコピー(なし鋳物を)一つのサブラスタを作成する必要があります。レンダリングのパイプラインが含まれているため、やや遅くなる可能性がありますが、それはまだ合理的に実行する必要があります。

// Get subimage "normal way" 
BufferedImage subimage = image.getSubimage(25, 25, 50, 50); 

// Create new empty image of same type 
BufferedImage subThree = new BufferedImage(50, 50, image.getType()); 

// Draw the subimage onto the new, empty copy 
Graphics2D g = subThree.createGraphics(); 
try { 
    g.drawImage(subimage, 0, 0, null); 
} 
finally { 
    g.dispose(); 
} 
+0

包括的な返信をありがとう! –

0

私は以前同じ問題を抱えていましたが、共有ラスタを望んでいませんでした。私が見つけた唯一の解決策は、サブイメージを表すBufferedImageを作成し、そのサブイメージにピクセルをコピーすることでした。 BufferedImage画像を考えると

本当に速い何かを持っているために、私は直接のDataBufferにアクセスすると、私はSystem.arraycopyのを(使用して配列をコピー(行ずつ)を作る)

関連する問題