capturePhoto method

  1. @override
Future<PickedFile?> capturePhoto({
  1. required bool allowCompression,
  2. required int compressionQuality,
  3. required bool withData,
})
override

Captures a photo using the device camera.

Platform implementations should override this method to handle camera capture on their respective platforms.

Implementation

@override
Future<PickedFile?> capturePhoto({
  required bool allowCompression,
  required int compressionQuality,
  required bool withData,
}) async {
  try {
    // Check if getUserMedia is supported
    if (!_isGetUserMediaSupported()) {
      throw PlatformException(
        code: 'CAMERA_NOT_SUPPORTED',
        message: 'Camera access is not supported in this browser.',
      );
    }

    // Request camera access
    final stream = await html.window.navigator.mediaDevices?.getUserMedia({
      'video': true,
    });

    if (stream == null) {
      throw PlatformException(
        code: 'CAMERA_ACCESS_DENIED',
        message: 'Camera access was denied.',
      );
    }

    // Create video element to display camera feed
    final video = html.VideoElement()
      ..srcObject = stream
      ..autoplay = true
      ..muted = true
      ..style.width = '100%'
      ..style.height = '100%';

    // Create canvas for capturing
    final canvas = html.CanvasElement();
    final context = canvas.context2D;

    // Create capture UI
    final result = await _showCameraDialog(video, canvas, context, stream);

    if (result != null) {
      // Process the captured image
      Uint8List imageBytes = result;

      if (allowCompression) {
        imageBytes = await _compressImage(imageBytes, compressionQuality);
      }

      // Generate a filename with timestamp
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final filename = 'captured_photo_$timestamp.jpg';

      // Create object URL for the captured image
      final blob = html.Blob([imageBytes], 'image/jpeg');
      final objectUrl = html.Url.createObjectUrlFromBlob(blob);

      return PickedFile(
        path: objectUrl,
        name: filename,
        size: imageBytes.length,
        mimeType: 'image/jpeg',
        bytes: withData ? imageBytes : null,
      );
    }

    return null;
  } catch (e) {
    if (e is PlatformException) {
      rethrow;
    }
    throw PlatformException(
      code: 'CAMERA_ERROR',
      message: 'Failed to capture photo: $e',
    );
  }
}