Masquer les données sensibles des images

Cloud Data Loss Prevention peut masquer le texte sensible d'une image. À l'aide des détecteurs d'infoTypes et de Cloud Vision, Cloud DLP inspecte une image à la recherche de texte, détecte les données sensibles au sein du texte, puis renvoie une image dans laquelle toutes les données sensibles correspondantes sont masquées par un rectangle opaque.

Prenons l'exemple des images "avant" et "après" suivantes. L'image d'origine est un exemple de fichier image type généré à partir de la numérisation d'un document papier. Dans cet exemple, Cloud DLP a été configuré pour masquer les numéros de sécurité sociale américains, les adresses e-mail et les numéros de téléphone à l'aide de rectangles de différentes couleurs, en fonction du contenu.

Image masquée avant et après (cliquez pour agrandir)
  1. Image numérisée avant masquage
  2. Image numérisée après masquage

Limites et points à noter

Tenez compte des points suivants lorsque vous masquez du contenu dans des images.

Types de fichiers compatibles

Cloud DLP peut masquer les données sensibles de nombreux types d'images, y compris JPEG, BMP et PNG. Pour en savoir plus, consultez Types de fichiers compatibles.

Le masquage du contenu n'est pas compatible avec les fichiers SVG, PDF, XLSX, PPTX et DOCX.

Identifier les limites

Lorsque les données des images sont masquées, les limites de résultats ne s'appliquent pas. Ils peuvent entraîner des résultats inattendus ou potentiellement incohérents, où seules certaines données sont masquées. Si vous incluez FindingLimits dans votre requête, Cloud DLP génère une erreur.

Avant de commencer

  1. Connectez-vous à votre compte Google Cloud. Si vous débutez sur Google Cloud, créez un compte pour évaluer les performances de nos produits en conditions réelles. Les nouveaux clients bénéficient également de 300 $ de crédits gratuits pour exécuter, tester et déployer des charges de travail.
  2. Dans Google Cloud Console, sur la page de sélection du projet, sélectionnez ou créez un projet Google Cloud.

    Accéder au sélecteur de projet

  3. Vérifiez que la facturation est activée pour votre projet Google Cloud. Découvrez comment vérifier si la facturation est activée sur un projet.

  4. Activez l'API DLP

    Activer l'API

  5. Créez un compte de service :

    1. Dans la console Google Cloud, accédez à la page Créer un compte de service.

      Accéder à la page "Créer un compte de service"
    2. Sélectionnez votre projet.
    3. Dans le champ Nom du compte de service, saisissez un nom. La console Google Cloud remplit le champ ID du compte de service en fonction de ce nom.

      Dans le champ Description du compte de service, saisissez une description. Exemple : Service account for quickstart.

    4. Cliquez sur Créer et continuer.
    5. Pour accorder l'accès à votre projet, attribuez le rôle Project > Owner à votre compte de service.

      Pour accorder le rôle, trouvez la liste Sélectionner un rôle, puis sélectionnez Project > Owner.

    6. Cliquez sur Continuer.
    7. Cliquez sur OK pour terminer la création du compte de service.

      Ne fermez pas la fenêtre de votre navigateur. Vous en aurez besoin lors de la tâche suivante.

  6. Créez une clé de compte de service :

    1. Dans la console Google Cloud, cliquez sur l'adresse e-mail du compte de service que vous avez créé.
    2. Cliquez sur Keys (Clés).
    3. Cliquez sur Ajouter une clé, puis sur Créer une clé.
    4. Cliquez sur Create (Créer). Un fichier de clé JSON est téléchargé sur votre ordinateur.
    5. Cliquez sur Close (Fermer).
  7. Définissez la variable d'environnement GOOGLE_APPLICATION_CREDENTIALS pour qu'elle pointe vers le chemin du fichier JSON contenant la clé de votre compte de service. Cette variable ne s'applique qu'à la session de shell actuelle. Par conséquent, si vous ouvrez une nouvelle session, vous devez de nouveau la définir.

  8. Installez Google Cloud CLI.
  9. Pour initialiser gcloudCLI, exécutez la commande suivante :

    gcloud init
  10. Dans Google Cloud Console, sur la page de sélection du projet, sélectionnez ou créez un projet Google Cloud.

    Accéder au sélecteur de projet

  11. Vérifiez que la facturation est activée pour votre projet Google Cloud. Découvrez comment vérifier si la facturation est activée sur un projet.

  12. Activez l'API DLP

    Activer l'API

  13. Créez un compte de service :

    1. Dans la console Google Cloud, accédez à la page Créer un compte de service.

      Accéder à la page "Créer un compte de service"
    2. Sélectionnez votre projet.
    3. Dans le champ Nom du compte de service, saisissez un nom. La console Google Cloud remplit le champ ID du compte de service en fonction de ce nom.

      Dans le champ Description du compte de service, saisissez une description. Exemple : Service account for quickstart.

    4. Cliquez sur Créer et continuer.
    5. Pour accorder l'accès à votre projet, attribuez le rôle Project > Owner à votre compte de service.

      Pour accorder le rôle, trouvez la liste Sélectionner un rôle, puis sélectionnez Project > Owner.

    6. Cliquez sur Continuer.
    7. Cliquez sur OK pour terminer la création du compte de service.

      Ne fermez pas la fenêtre de votre navigateur. Vous en aurez besoin lors de la tâche suivante.

  14. Créez une clé de compte de service :

    1. Dans la console Google Cloud, cliquez sur l'adresse e-mail du compte de service que vous avez créé.
    2. Cliquez sur Keys (Clés).
    3. Cliquez sur Ajouter une clé, puis sur Créer une clé.
    4. Cliquez sur Create (Créer). Un fichier de clé JSON est téléchargé sur votre ordinateur.
    5. Cliquez sur Close (Fermer).
  15. Définissez la variable d'environnement GOOGLE_APPLICATION_CREDENTIALS pour qu'elle pointe vers le chemin du fichier JSON contenant la clé de votre compte de service. Cette variable ne s'applique qu'à la session de shell actuelle. Par conséquent, si vous ouvrez une nouvelle session, vous devez de nouveau la définir.

  16. Installez Google Cloud CLI.
  17. Pour initialiser gcloudCLI, exécutez la commande suivante :

    gcloud init

Masquer tous les infoTypes par défaut d'une image

Pour masquer les données sensibles d'une image, envoyez l'image à la méthode image.redact de l'API DLP. Cloud DLP recherche les infoTypes les plus courants, à moins que vous ne spécifiez des types d'informations spécifiques (infoTypes) à rechercher.

Pour masquer les infoTypes par défaut d'une image, procédez comme suit:

  1. Encodez l'image en tant que chaîne en base64.

    Si vous prévoyez d'utiliser l'une des bibliothèques clientes Cloud DLP pour effectuer cette tâche, ignorez cette étape.

  2. Envoyez une requête à la méthode image.redact.

    Si vous souhaitez masquer les infoTypes par défaut, la requête ne requiert que l'image encodée en base64.

Par exemple, considérons l'image suivante. Voici un exemple de fichier image type généré à partir de la numérisation d'un document papier.

Image d'origine non masquée (cliquez pour agrandir)

Pour masquer les infoTypes par défaut de cette image, envoyez la requête suivante à la méthode image.redact de l'API DLP :

Protocole

{
  "byteItem": {
    "data": "[BASE64-ENCODED-IMAGE]",
    "type": "IMAGE_JPEG"
  }
}

Cloud DLP renvoie les éléments suivants :

    {
      "redactedImage": "[BASE64-ENCODED-IMAGE]"
    }

Décodez l'image encodée en base64.

Java

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ByteContentItem;
import com.google.privacy.dlp.v2.ByteContentItem.BytesType;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.RedactImageRequest;
import com.google.privacy.dlp.v2.RedactImageResponse;
import com.google.protobuf.ByteString;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

class RedactImageFileAllInfoTypes {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String inputPath = "src/test/resources/sensitive-data-image.jpeg";
    String outputPath = "sensitive-data-image-redacted.jpeg";
    redactImageFileAllInfoTypes(projectId, inputPath, outputPath);
  }

  static void redactImageFileAllInfoTypes(String projectId, String inputPath, String outputPath)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlp = DlpServiceClient.create()) {
      // Specify the content to be redacted.
      ByteString fileBytes = ByteString.readFrom(new FileInputStream(inputPath));
      ByteContentItem byteItem =
          ByteContentItem.newBuilder().setType(BytesType.IMAGE_JPEG).setData(fileBytes).build();

      // Construct the Redact request to be sent by the client.
      // Do not specify the type of info to redact.
      RedactImageRequest request =
          RedactImageRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setByteItem(byteItem)
              .build();

      // Use the client to send the API request.
      RedactImageResponse response = dlp.redactImage(request);

      // Parse the response and process results.
      FileOutputStream redacted = new FileOutputStream(outputPath);
      redacted.write(response.getRedactedImage().toByteArray());
      redacted.close();
      System.out.println("Redacted image written to " + outputPath);
    }
  }
}

L'image obtenue est la suivante :

Image masquée, tous les infoTypes (cliquez pour agrandir)

Notez qu'en plus de masquer le numéro de sécurité sociale manuscrit, l'adresse e-mail et le numéro de téléphone, Cloud DLP a également masqué l'année. La section suivante montre comment masquer uniquement certains infoTypes.

Masquer des infoTypes spécifiques dans une image

Si vous ne souhaitez masquer que certaines données sensibles dans une image, spécifiez les infoTypes intégrés correspondants.

Pour masquer des infoTypes spécifiques dans une image, envoyez une requête à la méthode image.redact de l'API DLP. La requête doit inclure les éléments suivants : * L'image. * Un ou plusieurs détecteurs d'infoTypes

Prenons l'exemple de l'image d'origine de la section précédente. Pour ne masquer que les numéros de sécurité sociale américains, les adresses e-mail et les numéros de téléphone, envoyez le code JSON suivant à la méthode image.redact de l'API DLP :

Protocole

    {
      "byteItem": {
        "data": "[BASE64-ENCODED-IMAGE]",
        "type": "IMAGE_JPEG"
      },
      "imageRedactionConfigs": [
        {
          "infoType": {
            "name": "US_SOCIAL_SECURITY_NUMBER"
          }
        },
        {
          "infoType": {
            "name": "EMAIL_ADDRESS"
          }
        },
        {
          "infoType": {
            "name": "PHONE_NUMBER"
          }
        }
      ]
    }

Cloud DLP renvoie les éléments suivants :

    {
      "redactedImage": "[BASE64-ENCODED-IMAGE]"
    }

Décodez l'image encodée en base64.

Java

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ByteContentItem;
import com.google.privacy.dlp.v2.ByteContentItem.BytesType;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.RedactImageRequest;
import com.google.privacy.dlp.v2.RedactImageRequest.ImageRedactionConfig;
import com.google.privacy.dlp.v2.RedactImageResponse;
import com.google.protobuf.ByteString;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class RedactImageFileListedInfoTypes {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String inputPath = "src/test/resources/sensitive-data-image.jpeg";
    String outputPath = "sensitive-data-image-redacted.jpeg";
    redactImageFileListedInfoTypes(projectId, inputPath, outputPath);
  }

  static void redactImageFileListedInfoTypes(String projectId, String inputPath, String outputPath)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlp = DlpServiceClient.create()) {
      // Specify the content to be redacted.
      ByteString fileBytes = ByteString.readFrom(new FileInputStream(inputPath));
      ByteContentItem byteItem =
          ByteContentItem.newBuilder().setType(BytesType.IMAGE_JPEG).setData(fileBytes).build();

      // Specify the types of info necessary to redact.
      List<InfoType> infoTypes = new ArrayList<>();
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      for (String typeName :
          new String[] {"US_SOCIAL_SECURITY_NUMBER", "EMAIL_ADDRESS", "PHONE_NUMBER"}) {
        infoTypes.add(InfoType.newBuilder().setName(typeName).build());
      }
      InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes).build();

      // Prepare redaction configs.
      List<ImageRedactionConfig> imageRedactionConfigs =
          infoTypes.stream()
              .map(infoType -> ImageRedactionConfig.newBuilder().setInfoType(infoType).build())
              .collect(Collectors.toList());

      // Construct the Redact request to be sent by the client.
      RedactImageRequest request =
          RedactImageRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setByteItem(byteItem)
              .addAllImageRedactionConfigs(imageRedactionConfigs)
              .setInspectConfig(inspectConfig)
              .build();

      // Use the client to send the API request.
      RedactImageResponse response = dlp.redactImage(request);

      // Parse the response and process results.
      FileOutputStream redacted = new FileOutputStream(outputPath);
      redacted.write(response.getRedactedImage().toByteArray());
      redacted.close();
      System.out.println("Redacted image written to " + outputPath);
    }
  }
}

C#

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using Google.Protobuf;
using System;
using System.IO;

public class RedactImage
{
    public static RedactImageResponse Redact(string projectId, string originalImagePath, string redactedImagePath)
    {
        var request = new RedactImageRequest
        {
            Parent = new LocationName(projectId, "global").ToString(),
            InspectConfig = new InspectConfig
            {
                MinLikelihood = Likelihood.Likely,
                Limits = new InspectConfig.Types.FindingLimits() { MaxFindingsPerItem = 5 },
                IncludeQuote = true,
                InfoTypes =
                    {
                        new InfoType { Name = "PHONE_NUMBER" },
                        new InfoType { Name = "EMAIL_ADDRESS" }
                    }
            },
            ByteItem = new ByteContentItem
            {
                Type = ByteContentItem.Types.BytesType.ImagePng,
                Data = ByteString.FromStream(new FileStream(originalImagePath, FileMode.Open))
            },
        };

        var client = DlpServiceClient.Create();
        var response = client.RedactImage(request);

        Console.WriteLine($"Extracted text: {response.ExtractedText}");

        // Writes redacted image into file
        response.RedactedImage.WriteTo(new FileStream(redactedImagePath, FileMode.Create, FileAccess.Write));

        return response;
    }
}

L'image obtenue est la suivante :

Image masquée, trois infoTypes (cliquez pour agrandir)

Vous pouvez appliquer un code couleur aux informations masquées par infoType lorsque vous souhaitez identifier les éléments masqués en un coup d'œil. Pour en savoir plus, consultez la section suivante.

Masquer les infoTypes d'une image avec des codes couleur

Pour attribuer des codes couleur aux informations masquées par infoType, associez des détecteurs d'infoTypes à des valeurs d'espace colorimétrique RVB.

Pour attribuer des codes couleur aux infoTypes masqués dans une image, envoyez une requête à la méthode image.redact de l'API DLP. La requête doit inclure les éléments suivants : * L'image. * Un ou plusieurs détecteurs d'infoTypes, chacun étant associé à une couleur utilisant des valeurs d'espace colorimétrique RVB.

Prenons l'exemple de l'image d'origine de la première section. Pour masquer les numéros de sécurité sociale américains avec un cadre violet, les adresses e-mail avec un cadre vert et les numéros de téléphone avec un cadre orange, envoyez le code JSON suivant à la méthode image.redact de l'API DLP :

Protocole

    {
      "byteItem": {
        "data": "[BASE64-ENCODED-IMAGE]",
        "type": "IMAGE_JPEG"
      },
      "imageRedactionConfigs": [
        {
          "infoType": {
            "name": "US_SOCIAL_SECURITY_NUMBER"
          },
          "redactionColor": {
            "red": 0.3,
            "green": 0.1,
            "blue": 0.6
          }
        },
        {
          "infoType": {
            "name": "EMAIL_ADDRESS"
          },
          "redactionColor": {
            "red": 0.5,
            "blue": 0.5,
            "green": 1
          }
        },
        {
          "infoType": {
            "name": "PHONE_NUMBER"
          },
          "redactionColor": {
            "red": 1,
            "blue": 0,
            "green": 0.6
          }
        }
      ]
    }

Cloud DLP renvoie les éléments suivants :

    {
      "redactedImage": "[BASE64-ENCODED-IMAGE]"
    }

Décodez l'image encodée en base64.

Java

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ByteContentItem;
import com.google.privacy.dlp.v2.ByteContentItem.BytesType;
import com.google.privacy.dlp.v2.Color;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.RedactImageRequest;
import com.google.privacy.dlp.v2.RedactImageRequest.ImageRedactionConfig;
import com.google.privacy.dlp.v2.RedactImageResponse;
import com.google.protobuf.ByteString;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class RedactImageFileColoredInfoTypes {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String inputPath = "src/test/resources/test.png";
    String outputPath = "redacted.png";
    redactImageFileColoredInfoTypes(projectId, inputPath, outputPath);
  }

  static void redactImageFileColoredInfoTypes(String projectId, String inputPath, String outputPath)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlp = DlpServiceClient.create()) {
      // Specify the content to be redacted.
      ByteString fileBytes = ByteString.readFrom(new FileInputStream(inputPath));
      ByteContentItem byteItem =
          ByteContentItem.newBuilder().setType(BytesType.IMAGE_JPEG).setData(fileBytes).build();

      // Define types of info to redact associate each one with a different color.
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      ImageRedactionConfig ssnRedactionConfig =
          ImageRedactionConfig.newBuilder()
              .setInfoType(InfoType.newBuilder().setName("US_SOCIAL_SECURITY_NUMBER").build())
              .setRedactionColor(Color.newBuilder().setRed(.3f).setGreen(.1f).setBlue(.6f).build())
              .build();
      ImageRedactionConfig emailRedactionConfig =
          ImageRedactionConfig.newBuilder()
              .setInfoType(InfoType.newBuilder().setName("EMAIL_ADDRESS").build())
              .setRedactionColor(Color.newBuilder().setRed(.5f).setGreen(.5f).setBlue(1).build())
              .build();
      ImageRedactionConfig phoneRedactionConfig =
          ImageRedactionConfig.newBuilder()
              .setInfoType(InfoType.newBuilder().setName("PHONE_NUMBER").build())
              .setRedactionColor(Color.newBuilder().setRed(1).setGreen(0).setBlue(.6f).build())
              .build();

      // Create collection of all redact configurations.
      List<ImageRedactionConfig> imageRedactionConfigs =
          Arrays.asList(ssnRedactionConfig, emailRedactionConfig, phoneRedactionConfig);

      // List types of info to search for.
      InspectConfig config =
          InspectConfig.newBuilder()
              .addAllInfoTypes(
                  imageRedactionConfigs.stream()
                      .map(ImageRedactionConfig::getInfoType)
                      .collect(Collectors.toList()))
              .build();

      // Construct the Redact request to be sent by the client.
      RedactImageRequest request =
          RedactImageRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setByteItem(byteItem)
              .addAllImageRedactionConfigs(imageRedactionConfigs)
              .setInspectConfig(config)
              .build();

      // Use the client to send the API request.
      RedactImageResponse response = dlp.redactImage(request);

      // Parse the response and process results.
      FileOutputStream redacted = new FileOutputStream(outputPath);
      redacted.write(response.getRedactedImage().toByteArray());
      redacted.close();
      System.out.println("Redacted image written to " + outputPath);
    }
  }
}

L'image obtenue est la suivante :

Image masquée, trois infoTypes avec code couleur (cliquez pour agrandir)

Masquer tout le texte d'une image

Cloud DLP contient également une option permettant de masquer tout le texte détecté dans une image.

Pour masquer tout le texte d'une image, envoyez une requête à la méthode image.redact de l'API DLP. La requête doit inclure les éléments suivants : * L'image. * L'option redactAllText définie sur true

Prenons l'exemple de l'image d'origine de la première section. Pour masquer tout le texte, envoyez le code JSON suivant à la méthode image.redact de l'API DLP :

Protocole

    {
      "byteItem": {
        "data": "[BASE64-ENCODED-IMAGE]",
        "type": "IMAGE_JPEG"
      },
      "imageRedactionConfigs": [
        {
          "redactAllText": true
        }
      ]
    }

Cloud DLP renvoie les éléments suivants :

    {
      "redactedImage": "[BASE64-ENCODED-IMAGE]"
    }

Décodez l'image encodée en base64.

Python

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

import google.cloud.dlp  # noqa: E402, F811

def redact_image_all_text(
    project: str,
    filename: str,
    output_filename: str,
) -> None:
    """Uses the Data Loss Prevention API to redact all text in an image.

    Args:
        project: The Google Cloud project id to use as a parent resource.
        filename: The path to the file to inspect.
        output_filename: The path to which the redacted image will be written.

    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Construct the image_redaction_configs, indicating to DLP that all text in
    # the input image should be redacted.
    image_redaction_configs = [{"redact_all_text": True}]

    # Construct the byte_item, containing the file's byte data.
    with open(filename, mode="rb") as f:
        byte_item = {"type_": google.cloud.dlp_v2.FileType.IMAGE, "data": f.read()}

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API.
    response = dlp.redact_image(
        request={
            "parent": parent,
            "image_redaction_configs": image_redaction_configs,
            "byte_item": byte_item,
        }
    )

    # Write out the results.
    with open(output_filename, mode="wb") as f:
        f.write(response.redacted_image)

    print(
        "Wrote {byte_count} to {filename}".format(
            byte_count=len(response.redacted_image), filename=output_filename
        )
    )

Java

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ByteContentItem;
import com.google.privacy.dlp.v2.ByteContentItem.BytesType;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.RedactImageRequest;
import com.google.privacy.dlp.v2.RedactImageRequest.ImageRedactionConfig;
import com.google.privacy.dlp.v2.RedactImageResponse;
import com.google.protobuf.ByteString;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

class RedactImageFileAllText {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project-id";
    String inputPath = "src/test/resources/sensitive-data-image.jpeg";
    String outputPath = "sensitive-data-image-redacted.jpeg";
    redactImageFileAllText(projectId, inputPath, outputPath);
  }

  static void redactImageFileAllText(String projectId, String inputPath, String outputPath)
      throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlp = DlpServiceClient.create()) {
      // Specify the content to be redacted.
      ByteString fileBytes = ByteString.readFrom(new FileInputStream(inputPath));
      ByteContentItem byteItem =
          ByteContentItem.newBuilder().setType(BytesType.IMAGE_JPEG).setData(fileBytes).build();

      // Enable redaction of all text.
      ImageRedactionConfig imageRedactionConfig =
          ImageRedactionConfig.newBuilder().setRedactAllText(true).build();

      // Construct the Redact request to be sent by the client.
      // Do not specify the type of info to redact.
      RedactImageRequest request =
          RedactImageRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setByteItem(byteItem)
              .addImageRedactionConfigs(imageRedactionConfig)
              .build();

      // Use the client to send the API request.
      RedactImageResponse response = dlp.redactImage(request);

      // Parse the response and process results.
      FileOutputStream redacted = new FileOutputStream(outputPath);
      redacted.write(response.getRedactedImage().toByteArray());
      redacted.close();
      System.out.println("Redacted image written to " + outputPath);
    }
  }
}

L'API renvoie les images que vous lui avez fournies, mais tout texte identifié par vos critères comme contenant des informations sensibles est masqué.

L'image obtenue est la suivante :

Image masquée, tout le texte (cliquez pour agrandir)

Exemples de code

Vous trouverez ci-après des exemples de code dans plusieurs langages qui montrent comment masquer du texte sensible contenu dans une image à l'aide de Cloud DLP.

Node.js

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Imports required Node.js libraries
const mime = require('mime');
const fs = require('fs');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under
// const projectId = 'my-project';

// The path to a local file to inspect. Can be a JPG or PNG image file.
// const filepath = 'path/to/image.png';

// The minimum likelihood required before redacting a match
// const minLikelihood = 'LIKELIHOOD_UNSPECIFIED';

// The infoTypes of information to redact
// const infoTypes = [{ name: 'EMAIL_ADDRESS' }, { name: 'PHONE_NUMBER' }];

// The local path to save the resulting image to.
// const outputPath = 'result.png';
async function redactImage() {
  const imageRedactionConfigs = infoTypes.map(infoType => {
    return {infoType: infoType};
  });

  // Load image
  const fileTypeConstant =
    ['image/jpeg', 'image/bmp', 'image/png', 'image/svg'].indexOf(
      mime.getType(filepath)
    ) + 1;
  const fileBytes = Buffer.from(fs.readFileSync(filepath)).toString('base64');

  // Construct image redaction request
  const request = {
    parent: `projects/${projectId}/locations/global`,
    byteItem: {
      type: fileTypeConstant,
      data: fileBytes,
    },
    inspectConfig: {
      minLikelihood: minLikelihood,
      infoTypes: infoTypes,
    },
    imageRedactionConfigs: imageRedactionConfigs,
  };

  // Run image redaction request
  const [response] = await dlp.redactImage(request);
  const image = response.redactedImage;
  fs.writeFileSync(outputPath, image);
  console.log(`Saved image redaction results to path: ${outputPath}`);
}
redactImage();

Python

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

import mimetypes

import google.cloud.dlp

def redact_image(
    project: str,
    filename: str,
    output_filename: str,
    info_types: List[str],
    min_likelihood: str = None,
    mime_type: str = None,
) -> None:
    """Uses the Data Loss Prevention API to redact protected data in an image.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        filename: The path to the file to inspect.
        output_filename: The path to which the redacted image will be written.
        info_types: A list of strings representing info types to look for.
            A full list of info type categories can be fetched from the API.
        min_likelihood: A string representing the minimum likelihood threshold
            that constitutes a match. One of: 'LIKELIHOOD_UNSPECIFIED',
            'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE', 'LIKELY', 'VERY_LIKELY'.
        mime_type: The MIME type of the file. If not specified, the type is
            inferred via the Python standard library's mimetypes module.
    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Prepare info_types by converting the list of strings into a list of
    # dictionaries (protos are also accepted).
    info_types = [{"name": info_type} for info_type in info_types]

    # Prepare image_redaction_configs, a list of dictionaries. Each dictionary
    # contains an info_type and optionally the color used for the replacement.
    # The color is omitted in this sample, so the default (black) will be used.
    image_redaction_configs = []

    if info_types is not None:
        for info_type in info_types:
            image_redaction_configs.append({"info_type": info_type})

    # Construct the configuration dictionary. Keys which are None may
    # optionally be omitted entirely.
    inspect_config = {
        "min_likelihood": min_likelihood,
        "info_types": info_types,
    }

    # If mime_type is not specified, guess it from the filename.
    if mime_type is None:
        mime_guess = mimetypes.MimeTypes().guess_type(filename)
        mime_type = mime_guess[0] or "application/octet-stream"

    # Select the content type index from the list of supported types.
    supported_content_types = {
        None: 0,  # "Unspecified"
        "image/jpeg": 1,
        "image/bmp": 2,
        "image/png": 3,
        "image/svg": 4,
        "text/plain": 5,
    }
    content_type_index = supported_content_types.get(mime_type, 0)

    # Construct the byte_item, containing the file's byte data.
    with open(filename, mode="rb") as f:
        byte_item = {"type_": content_type_index, "data": f.read()}

    # Convert the project id into a full resource id.
    parent = f"projects/{project}"

    # Call the API.
    response = dlp.redact_image(
        request={
            "parent": parent,
            "inspect_config": inspect_config,
            "image_redaction_configs": image_redaction_configs,
            "byte_item": byte_item,
        }
    )

    # Write out the results.
    with open(output_filename, mode="wb") as f:
        f.write(response.redacted_image)
    print(
        "Wrote {byte_count} to {filename}".format(
            byte_count=len(response.redacted_image), filename=output_filename
        )
    )

Go

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// redactImage blacks out the identified portions of the input image (with type bytesType)
// and stores the result in outputPath.
func redactImage(w io.Writer, projectID string, infoTypeNames []string, bytesType dlppb.ByteContentItem_BytesType, inputPath, outputPath string) error {
	// projectID := "my-project-id"
	// infoTypeNames := []string{"US_SOCIAL_SECURITY_NUMBER"}
	// bytesType := dlppb.ByteContentItem_IMAGE_PNG
	// inputPath := /tmp/input
	// outputPath := /tmp/output

	ctx := context.Background()

	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %w", err)
	}
	defer client.Close()

	// Convert the info type strings to a list of InfoTypes.
	var infoTypes []*dlppb.InfoType
	for _, it := range infoTypeNames {
		infoTypes = append(infoTypes, &dlppb.InfoType{Name: it})
	}

	// Convert the info type strings to a list of types to redact in the image.
	var redactInfoTypes []*dlppb.RedactImageRequest_ImageRedactionConfig
	for _, it := range infoTypeNames {
		redactInfoTypes = append(redactInfoTypes, &dlppb.RedactImageRequest_ImageRedactionConfig{
			Target: &dlppb.RedactImageRequest_ImageRedactionConfig_InfoType{
				InfoType: &dlppb.InfoType{Name: it},
			},
		})
	}

	// Read the input file.
	b, err := ioutil.ReadFile(inputPath)
	if err != nil {
		return fmt.Errorf("ioutil.ReadFile: %w", err)
	}

	// Create a configured request.
	req := &dlppb.RedactImageRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
		InspectConfig: &dlppb.InspectConfig{
			InfoTypes:     infoTypes,
			MinLikelihood: dlppb.Likelihood_POSSIBLE,
		},
		// The item to analyze.
		ByteItem: &dlppb.ByteContentItem{
			Type: bytesType,
			Data: b,
		},
		ImageRedactionConfigs: redactInfoTypes,
	}
	// Send the request.
	resp, err := client.RedactImage(ctx, req)
	if err != nil {
		return fmt.Errorf("RedactImage: %w", err)
	}
	// Write the output file.
	if err := ioutil.WriteFile(outputPath, resp.GetRedactedImage(), 0644); err != nil {
		return fmt.Errorf("ioutil.WriteFile: %w", err)
	}
	fmt.Fprintf(w, "Wrote output to %s", outputPath)
	return nil
}

PHP

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

use Google\Cloud\Dlp\V2\DlpServiceClient;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\RedactImageRequest\ImageRedactionConfig;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\ByteContentItem;

/**
 * Redact sensitive data from an image.
 *
 * @param string $callingProjectId    The project ID to run the API call under
 * @param string $imagePath           The local filepath of the image to inspect
 * @param string $outputPath          The local filepath to save the resulting image to
 */
function redact_image(
    string $callingProjectId,
    string $imagePath,
    string $outputPath
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // The infoTypes of information to match
    $phoneNumberInfoType = (new InfoType())
        ->setName('PHONE_NUMBER');
    $infoTypes = [$phoneNumberInfoType];

    // The minimum likelihood required before returning a match
    $minLikelihood = likelihood::LIKELIHOOD_UNSPECIFIED;

    // Whether to include the matching string in the response
    $includeQuote = true;

    // Create the configuration object
    $inspectConfig = (new InspectConfig())
        ->setMinLikelihood($minLikelihood)
        ->setInfoTypes($infoTypes);

    // Read image file into a buffer
    $imageRef = fopen($imagePath, 'rb');
    $imageBytes = fread($imageRef, filesize($imagePath));
    fclose($imageRef);

    // Get the image's content type
    $typeConstant = (int) array_search(
        mime_content_type($imagePath),
        [false, 'image/jpeg', 'image/bmp', 'image/png', 'image/svg']
    );

    // Create the byte-storing object
    $byteContent = (new ByteContentItem())
        ->setType($typeConstant)
        ->setData($imageBytes);

    // Create the image redaction config objects
    $imageRedactionConfigs = [];
    foreach ($infoTypes as $infoType) {
        $config = (new ImageRedactionConfig())
            ->setInfoType($infoType);
        $imageRedactionConfigs[] = $config;
    }

    $parent = "projects/$callingProjectId/locations/global";

    // Run request
    $response = $dlp->redactImage([
        'parent' => $parent,
        'inspectConfig' => $inspectConfig,
        'byteItem' => $byteContent,
        'imageRedactionConfigs' => $imageRedactionConfigs
    ]);

    // Save result to file
    file_put_contents($outputPath, $response->getRedactedImage());

    // Print completion message
    print('Redacted image saved to ' . $outputPath . PHP_EOL);
}

C#

Pour savoir comment installer et utiliser la bibliothèque cliente pour Cloud DLP, consultez Bibliothèques clientes Cloud DLP.

Pour vous authentifier auprès de Cloud DLP, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;
using Google.Protobuf;
using System;
using System.IO;

public class RedactImage
{
    public static RedactImageResponse Redact(string projectId, string originalImagePath, string redactedImagePath)
    {
        var request = new RedactImageRequest
        {
            Parent = new LocationName(projectId, "global").ToString(),
            InspectConfig = new InspectConfig
            {
                MinLikelihood = Likelihood.Likely,
                Limits = new InspectConfig.Types.FindingLimits() { MaxFindingsPerItem = 5 },
                IncludeQuote = true,
                InfoTypes =
                    {
                        new InfoType { Name = "PHONE_NUMBER" },
                        new InfoType { Name = "EMAIL_ADDRESS" }
                    }
            },
            ByteItem = new ByteContentItem
            {
                Type = ByteContentItem.Types.BytesType.ImagePng,
                Data = ByteString.FromStream(new FileStream(originalImagePath, FileMode.Open))
            },
        };

        var client = DlpServiceClient.Create();
        var response = client.RedactImage(request);

        Console.WriteLine($"Extracted text: {response.ExtractedText}");

        // Writes redacted image into file
        response.RedactedImage.WriteTo(new FileStream(redactedImagePath, FileMode.Create, FileAccess.Write));

        return response;
    }
}

Essayer

Vous pouvez tester chacun des exemples de cette page par vous-même ou tester vos propres images dans APIs Explorer sur la page de référence de la méthode image.redact :

Accéder à APIs Explorer

Étapes suivantes