關鍵Code:
@Override public void onPictureTaken(byte[] data, Camera camera) { try { ByteArrayInputStream stream = new ByteArrayInputStream(data); Bitmap bitmap = BitmapFactory.decodeStream(stream); stream.close(); stream = null; // 螢幕解析度 Point screenSize = new Point(); getWindowManager().getDefaultDisplay().getSize(screenSize); // 照片解析度 / 預覽解析度 = 照片倍率 float widthRate = picWidth >= pvWidth ? picWidth / pvWidth : pvWidth / picWidth; float heightRate = picHeight >= pvHeight ? picHeight / pvHeight : pvHeight / picHeight; // 預覽解析度/螢幕解析度 = 差異倍率 float screenWidthRate = screenSize.x >= pvWidth ? screenSize.x / pvWidth : pvWidth / screenSize.x; float screenHeightRate = screenSize.y >= pvHeight ? screenSize.y / pvHeight : pvHeight / screenSize.y; // 取得ImageView x,y int[] location = new int[2]; imageview.getLocationOnScreen(location); // 求得新座標 location[0] *= screenWidthRate * widthRate; location[1] *= screenHeightRate * heightRate; // 求得新尺寸 int newWidth = (int) (imageview.getWidth() * widthRate * screenWidthRate); int newHeight = (int) (imageview.getHeight() * heightRate * screenHeightRate); // 擷取範圍 Bitmap bitmapRect = Bitmap.createBitmap(bitmap, location[0], location[1], newWidth, newHeight); bitmap = null; FileOutputStream fileOutputStream = new FileOutputStream( new File("/sdcard/" + new Date().getTime() + ".jpg")); bitmapRect.compress(CompressFormat.JPEG, 90, fileOutputStream); // 寫入檔案 fileOutputStream.flush(); fileOutputStream.close(); fileOutputStream = null; toralR = 0; totalG = 0; totalB = 0; int count = 0; for (int w = 0; w < bitmapRect.getWidth(); w++) { for (int h = 0; h < bitmapRect.getHeight(); h++) { count++; int pixel = bitmapRect.getPixel(w, h); toralR += Color.red(pixel); totalG += Color.green(pixel); totalB += Color.blue(pixel); } } toralR /= count; totalG /= count; totalB /= count; Toast.makeText(MainActivity.this, "Red:" + toralR + ", Green:" + totalG + ", Blue:" + totalB, 1).show(); bitmapRect = null; // 重啟相機預覽功能 camera.startPreview(); } catch (IOException e) { Log.i("Tack_IOException", e.getMessage()); } }
執行結果: