案例一:http://www.java-gaming.org/index.php/topic,24988.0Thanks for everybody
Java code: change Java Image to int[] for JNI warpper
Image image = null;
try {
File file = new File("c:/image.jpg");
image = ImageIO.read(file);
}
catch (MalformedURLException ex) {
Logger.getLogger(SmartTest.class.getName()).log(Level.SEVERE, ex.getMessage());
} catch (IOException ex) {
Logger.getLogger(SmartTest.class.getName()).log(Level.SEVERE, ex.getMessage());
}
// Image grabbing
int[] pixels = new int[w * h];
PixelGrabber pg = new PixelGrabber(image, x, y, w, h, pixels, 0, w);
try {
pg.grabPixels();
}catch (InterruptedException e) {
System.err.println("interrupted waiting for pixels!");
return;
}
if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
System.err.println("image fetch aborted or errored");
return;
}
JNI wrapper code(C++): change int[] of Java Image to C++ BITMAP
HBITMAP CreateBitmapFromPixel( HDC hDC, UINT uWidth, UINT uHeight, UINT uBitsPerPixel, LPVOID pBits )
{
HBITMAP m_HBitmap = NULL;
if ( !uWidth || !uHeight || !uBitsPerPixel )
{
return m_HBitmap;//hBitmap;
}
LONG lBmpSize = uWidth * uHeight * uBitsPerPixel / 8;
BITMAPINFO bmpInfo = { 0 };
bmpInfo.bmiHeader.biBitCount = uBitsPerPixel;
bmpInfo.bmiHeader.biHeight = uHeight;
bmpInfo.bmiHeader.biWidth = uWidth;
bmpInfo.bmiHeader.biPlanes = 1;
bmpInfo.bmiHeader.biSizeImage = uWidth * uHeight * uBitsPerPixel / 8;
bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
// Pointer to access the pixels of bitmap
UINT * pPixels = 0;
/*hBitmap*/m_HBitmap = CreateDIBSection( hDC, (BITMAPINFO *)&bmpInfo, DIB_RGB_COLORS, (void **)& pPixels , NULL, 0);
if ( !m_HBitmap )
return m_HBitmap;//hBitmap; // return if invalid bitmaps
SetBitmapBits( m_HBitmap, lBmpSize,pBits);
return m_HBitmap;
}
sample code to change Java Image to BITMAP in JNIwrapper :
int len = env->GetArrayLength(pixels); //pixels is jintArray and get from input parameter
jint* jarr;
jarr = env->GetIntArrayElements(pixels,FALSE);
HBITMAP hImg = CreateBitmapFromPixel(pFront->bmp.hdcColor,(DWORD)cx,(DWORD)cy,32,jarr);
if( hImg != NULL )
{
DIBSECTION dib;
BITMAPINFO bi;
::GetObject( hImg, sizeof(dib), &dib );
bi.bmiHeader = dib.dsBmih;
// HDC is Hardware Device context. For understand how to set it please read Microsoft MSDN
// w and h in here are belongs to BITMAP buffer based on you HDC
::SetDIBitsToDevice(HDC, 0, 0,w,h,0, 0, 0,dib.dsBm.bmHeight,dib.dsBm.bmBits,&bi,DIB_RGB_COLORS);
DeleteObject( hImg );
}