1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
| import android.content.Context import android.graphics.Bitmap import android.graphics.Matrix import android.util.Log import android.util.Size import android.view.View import androidx.camera.core.CameraSelector import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.camera.core.Preview import androidx.camera.core.UseCaseGroup import androidx.camera.core.resolutionselector.AspectRatioStrategy import androidx.camera.core.resolutionselector.ResolutionSelector import androidx.camera.core.resolutionselector.ResolutionStrategy import androidx.camera.lifecycle.ProcessCameraProvider import androidx.camera.view.PreviewView import androidx.core.content.ContextCompat import androidx.lifecycle.LifecycleOwner import com.xhkjedu.zxs_android.utils.common.ZDeviceUtils
object ZCameraUtils { fun getCameraSelector(): CameraSelector { val systemModel = ZDeviceUtils.getSystemModel() val backArr = arrayOf("G156JW_A13") return if (systemModel in backArr) { CameraSelector.DEFAULT_BACK_CAMERA } else { CameraSelector.DEFAULT_FRONT_CAMERA } }
fun rotateBitmap(bm: Bitmap, degree: Float): Bitmap { val matrix: Matrix = Matrix() matrix.setRotate( degree, bm.getWidth() / 2f, bm.getHeight() / 2f )
return Bitmap.createBitmap( bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true ) }
fun Bitmap.rotate180(): Bitmap { return rotateBitmap(this, 180f) }
fun Bitmap.mirrorHorizontal(): Bitmap { if (this.isRecycled) return this
val matrix = Matrix().apply { postScale(-1f, 1f) postTranslate(width.toFloat(), 0f) }
return try { Bitmap.createBitmap(this, 0, 0, width, height, matrix, true) } catch (e: OutOfMemoryError) { e.printStackTrace() this } }
fun Bitmap.mirrorVertical(): Bitmap { if (this.isRecycled) return this
val matrix = Matrix().apply { postScale(1f, -1f) postTranslate(0f, height.toFloat()) }
return try { Bitmap.createBitmap(this, 0, 0, width, height, matrix, true) } catch (e: OutOfMemoryError) { e.printStackTrace() this } }
fun bindCameraUseCases( previewView: PreviewView?, context: Context, lifecycleOwner: LifecycleOwner, onImageCaptureReady: (ImageCapture) -> Unit ) { if (previewView == null) return val cameraProviderFuture = ProcessCameraProvider.getInstance(context) cameraProviderFuture.addListener({ val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
val aspectStrategy = AspectRatioStrategy.RATIO_4_3_FALLBACK_AUTO_STRATEGY
val previewSelector = ResolutionSelector.Builder() .setAspectRatioStrategy(aspectStrategy) .setResolutionStrategy( ResolutionStrategy( Size(1440, 1080), ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER ) ) .build()
val captureSelector = ResolutionSelector.Builder() .setAllowedResolutionMode(ResolutionSelector.PREFER_HIGHER_RESOLUTION_OVER_CAPTURE_RATE) .setAspectRatioStrategy(aspectStrategy) .setResolutionStrategy(ResolutionStrategy.HIGHEST_AVAILABLE_STRATEGY) .build()
fun bindWhenViewportReady() { val viewPort = previewView.viewPort if (viewPort == null || previewView.width == 0 || previewView.height == 0) { return }
val rotation = previewView.display.rotation
val preview = Preview.Builder() .setResolutionSelector(previewSelector) .setTargetRotation(rotation) .build() .also { it.surfaceProvider = previewView.surfaceProvider }
val imageCapture = ImageCapture.Builder() .setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY) .setJpegQuality(100) .setResolutionSelector(captureSelector) .setTargetRotation(rotation) .build()
onImageCaptureReady(imageCapture) cameraProvider.unbindAll() val group = UseCaseGroup.Builder() .setViewPort(viewPort) .addUseCase(preview) .addUseCase(imageCapture) .build() cameraProvider.bindToLifecycle( lifecycleOwner, getCameraSelector(), group ) }
val layoutListener = object : View.OnLayoutChangeListener { override fun onLayoutChange( v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int ) { if (previewView.width > 0 && previewView.height > 0 && previewView.viewPort != null) { previewView.removeOnLayoutChangeListener(this) bindWhenViewportReady() } } }
fun scheduleBind() { previewView.post { if (previewView.width > 0 && previewView.height > 0 && previewView.viewPort != null) { bindWhenViewportReady() } else { previewView.addOnLayoutChangeListener(layoutListener) } } }
if (previewView.isAttachedToWindow) { scheduleBind() } else { previewView.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener { override fun onViewAttachedToWindow(v: View) { previewView.removeOnAttachStateChangeListener(this) scheduleBind() }
override fun onViewDetachedFromWindow(v: View) {} }) } }, ContextCompat.getMainExecutor(context)) }
fun takeHighQualityPhoto( context: Context, imageCapture: ImageCapture?, rotation: Int, onImageCaptured: (Bitmap) -> Unit, onError: (String) -> Unit = {} ) { val capture = imageCapture ?: run { onError("ImageCapture 未初始化") return }
capture.targetRotation = rotation
capture.takePicture( ContextCompat.getMainExecutor(context), object : ImageCapture.OnImageCapturedCallback() { override fun onError(exc: ImageCaptureException) { Log.e("CameraX", "拍照失败: ${exc.message}", exc) onError(exc.message ?: "拍照失败") }
override fun onCaptureSuccess(image: androidx.camera.core.ImageProxy) { try { val bitmap = image.toBitmap() onImageCaptured(bitmap) Log.d("CameraX", "高质量拍照成功: ${bitmap.width}x${bitmap.height}") } catch (e: Exception) { Log.e("CameraX", "Bitmap转换失败", e) onError("Bitmap转换失败") } finally { image.close() } } } ) } }
|