티스토리 뷰
Android
[Android] GLSurfaceView 캡처 → Bitmap → JPEG 변환 후, Retrofit2 post 이미지 전송(1)
EnvEng10 2020. 10. 19. 10:09반응형
1. GLSurfaceView 캡처 → Bitmap 변환
private Bitmap shareBitmap;
private Bitmap tempBitmap;
private GLSurfaceView mSurfaceView;
private ImageView iv_capture;
private interface BitmapReadyCallbacks { // callback
void onBitmapReady(Bitmap bitmap);
}
// 얘를 실행하면 캡처
private void captureGLSurface() {
captureBitmap(new BitmapReadyCallbacks() {
@Override
public void onBitmapReady(Bitmap bitmap) {
iv_capture.setImageBitmap(bitmap); // 캡처 set
iv_capture.setVisibility(VISIBLE); // 캡처 확인
shareBitmap = bitmap; // shareBitmap 에 저장
}
});
}
// 캡처 로직 리턴값을 tempBitmap 에 담고 callback 으로 전달
private void captureBitmap(final BitmapReadyCallbacks bitmapReadyCallbacks) {
mSurfaceView.queueEvent(new Runnable() {
@Override
public void run() {
EGL10 egl = (EGL10) EGLContext.getEGL();
GL10 gl = (GL10) egl.eglGetCurrentContext().getGL();
tempBitmap = createBitmapFromGLSurface(0, 0, mSurfaceView.getWidth(), mSurfaceView.getHeight(), gl);
runOnUiThread(new Runnable() {
@Override
public void run() {
bitmapReadyCallbacks.onBitmapReady(tempBitmap);
}
});
}
});
}
// 캡처 로직
private Bitmap createBitmapFromGLSurface(int x, int y, int w, int h, GL10 gl) {
int bitmapBuffer[] = new int[w * h];
int bitmapSource[] = new int[w * h];
IntBuffer intBuffer = IntBuffer.wrap(bitmapBuffer);
intBuffer.position(0);
try {
gl.glReadPixels(x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, intBuffer);
int offset1, offset2;
for (int i = 0; i < h; i++) {
offset1 = i * w;
offset2 = (h - i - 1) * w;
for (int j = 0; j < w; j++) {
int texturePixel = bitmapBuffer[offset1 + j];
int blue = (texturePixel >> 16) & 0xff;
int red = (texturePixel << 16) & 0x00ff0000;
int pixel = (texturePixel & 0xff00ff00) | red | blue;
bitmapSource[offset2 + j] = pixel;
}
}
} catch (GLException e) {
return null;
}
return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888);
}
2. Bitmap → JPEG 변환
1번에서 저장한 shareBitmap 을 JPEG 으로 변환
Bitmap bitmap = shareBitmap;
File file = new File(getContext().getCacheDir(), "file_name.jpeg");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] bitmapData = bos.toByteArray();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fos.write(bitmapData);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
JPEG 으로 변환된 FILE 을 POST해보자(2부로 ~)
참고 - Stack Overflow
반응형
'Android' 카테고리의 다른 글
[Android] 이미지 슬라이드 + Retrofit2 (AdapterViewFlipper) (0) | 2020.11.25 |
---|---|
Collection Framework (0) | 2020.11.25 |
[Android] Broadcast Receiver 를 이용한 App 자동 실행(전원이 켜질때) (0) | 2020.10.19 |
[Android] Circular ProgressBar 설정 (0) | 2020.10.19 |
[Android] GLSurfaceView 캡처 → Bitmap → JPEG 변환 후, Retrofit2 post 이미지 전송(2) (0) | 2020.10.19 |
댓글