Sensible Daten aus Bildern entfernen

Mit der Cloud Data Loss Prevention API können Sie sensiblen Text und Objekte in einem Bild erkennen und dann eine bearbeitete Version dieses Bilds abrufen. Im zurückgegebenen Bild werden die erkannten sensiblen Datenelemente durch ein undurchsichtiges Rechteck verdeckt. Mit infoType-Detektoren geben Sie die Arten von Informationen an, die erkannt und unkenntlich gemacht werden sollen.

Standardmäßig verwendet Sensitive Data Protection schwarze Rechtecke, um den entfernten Inhalt zu verdecken. Sie können jedoch für jeden infoType in der Konfiguration zum Entfernen von Daten aus Bildern eine Farbe angeben.

Entfernen von Text

Der Schutz sensibler Daten verwendet die optische Zeichenerkennung (Optical Character Recognition, OCR), um Text in Bildern zu erkennen. Sie können Folgendes in einem Bild unkenntlich machen:

Sehen Sie sich zum Beispiel die folgenden Bilder an. Das Originalbild ist ein Bild eines Dokuments, das Kontaktdaten enthält. In diesem Beispiel wurde Sensitive Data Protection so konfiguriert, dass alle Texte entfernt werden, die den infoTypes PERSON_NAME, EMAIL_ADDRESS und PHONE_NUMBER entsprechen. Das resultierende Bild enthält schwarze Rechtecke, die den erkannten vertraulichen Text verdecken.

Bild vor und nach dem Entfernen von Daten.
Vor und nach dem Entfernen von Text in einem Bild (zum Vergrößern klicken).

Objekt-Schwärzung

Sie können Sensitive Data Protection so konfigurieren, dass Objekte, die in der Regel sensible Informationen enthalten, unkenntlich gemacht werden.

Sehen Sie sich zum Beispiel die folgenden Bilder an. Das Originalbild ist ein KI-generiertes Bild mit einem Barcode, einem Nummernschild und einem Whiteboard. In diesem Beispiel wurde Sensitive Data Protection so konfiguriert, dass Objekte, die den infoTypes OBJECT_TYPE/BARCODE, OBJECT_TYPE/LICENSE_PLATE und OBJECT_TYPE/WHITEBOARD entsprechen, unkenntlich gemacht werden. Das resultierende Bild enthält farbige Rechtecke, die die erkannten vertraulichen Objekte abdecken. Jedem infoType wird eine Farbe zugewiesen.

Ein Bild mit potenziell sensiblen Objekten und dasselbe Bild mit unkenntlich gemachten Objekten.
Vor und nach der Unkenntlichmachung von Objekten in einem Bild (zum Vergrößern klicken).

Eine vollständige Liste der verfügbaren infoType-Detektoren für Objekte finden Sie unter Objekte in Bildern.

Einschränkungen und Überlegungen

Beachten Sie beim Entfernen von Inhalten aus Bildern Folgendes:

Unterstützte Dateitypen

Der Schutz sensibler Daten kann sensible Daten aus vielen Bildtypen entfernen, einschließlich JPEG, BMP und PNG. Weitere Informationen finden Sie unter Unterstützte Dateitypen.

Das Entfernen von Inhalten wird für SVG-, PDF-, XLSX-, PPTX- oder DOCX-Dateien nicht unterstützt.

Limits für die Konfiguration der Prüfung

Wenn Sie Daten aus Bildern entfernen, können Sie limits nicht in Ihre Inspektionskonfiguration aufnehmen. Grenzwerte können zu unerwarteten oder potenziell inkonsistenten Ergebnissen führen, wenn nur einige Daten entfernt werden. Wenn Sie das Feld limits in Ihrer Anfrage festlegen, gibt Sensitive Data Protection einen Fehler aus.

Hinweise

Bevor Sie mit den Aufgaben auf dieser Seite beginnen, müssen Sie die Authentifizierung einrichten und die erforderlichen IAM-Berechtigungen abrufen. Sie können Ihr Google Cloud-Nutzerkonto oder ein Dienstkonto verwenden. Achten Sie in beiden Fällen darauf, dass das von Ihnen verwendete Konto eine Rolle mit der Berechtigung serviceusage.services.use hat, z. B. „DLP-Administrator“ (roles/dlp.admin), „DLP-Nutzer“ (roles/dlp.user) oder eine benutzerdefinierte Rolle.

  1. Select the tab for how you plan to use the samples on this page:

    C#

    Wenn Sie die .NET Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Weitere Informationen finden Sie in der Dokumentation zur Google Cloud -Authentifizierung unter ADC für eine lokale Entwicklungsumgebung einrichten.

    Go

    Wenn Sie die Go Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Weitere Informationen finden Sie in der Dokumentation zur Google Cloud -Authentifizierung unter ADC für eine lokale Entwicklungsumgebung einrichten.

    Java

    Wenn Sie die Java Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Weitere Informationen finden Sie in der Dokumentation zur Google Cloud -Authentifizierung unter ADC für eine lokale Entwicklungsumgebung einrichten.

    Node.js

    Wenn Sie die Node.js Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Weitere Informationen finden Sie in der Dokumentation zur Google Cloud -Authentifizierung unter ADC für eine lokale Entwicklungsumgebung einrichten.

    PHP

    Wenn Sie die PHP Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Weitere Informationen finden Sie in der Dokumentation zur Google Cloud -Authentifizierung unter ADC für eine lokale Entwicklungsumgebung einrichten.

    Python

    Wenn Sie die Python Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

    1. Install the Google Cloud CLI.

    2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    3. To initialize the gcloud CLI, run the following command:

      gcloud init
    4. If you're using a local shell, then create local authentication credentials for your user account:

      gcloud auth application-default login

      You don't need to do this if you're using Cloud Shell.

      If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    Weitere Informationen finden Sie in der Dokumentation zur Google Cloud -Authentifizierung unter ADC für eine lokale Entwicklungsumgebung einrichten.

    REST

    Verwenden Sie die von der gcloud CLI bereitgestellten Anmeldedaten, um die REST API-Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung zu verwenden.

      After installing the Google Cloud CLI, initialize it by running the following command:

      gcloud init

      If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

    Weitere Informationen finden Sie in der Dokumentation zur Google Cloud -Authentifizierung unter Für die Verwendung von REST authentifizieren.

    Die image.redact-Methode unterstützt auch API-Schlüssel. Wenn Sie API-Schlüssel für die Authentifizierung verwenden möchten, müssen Sie keine lokale ADC-Datei (Standardanmeldedaten für Anwendungen) einrichten. Weitere Informationen unter Erstellen eines API-Schlüssels in der Google Cloud Authentifizierungsdokumentation.

    Informationen zum Einrichten der Authentifizierung für eine Produktionsumgebung finden Sie in der Google Cloud -Authentifizierungsdokumentation unter Set up Application Default Credentials for code running on Google Cloud.

  2. Bitten Sie Ihren Administrator, Ihnen die IAM-Rolle DLP User (roles/dlp.user) für Ihr Projekt zuzuweisen, um die Berechtigungen zu erhalten, die Sie zum Prüfen, Schwärzen und Anonymisieren von Inhalten benötigen. Weitere Informationen zum Zuweisen von Rollen finden Sie unter Zugriff auf Projekte, Ordner und Organisationen verwalten.

    Sie können die erforderlichen Berechtigungen auch über benutzerdefinierte Rollen oder andere vordefinierte Rollen erhalten.

  3. Alle Standard-infoTypes aus einem Bild entfernen

    Senden Sie ein Bild an die Methode image.redact der DLP API, um sensible Daten aus einem Bild zu entfernen Wenn Sie nicht nach bestimmten Informationstypen (infoTypes) suchen, sucht Sensitive Data Protection nach den häufigsten infoTypes.

    Standard-InfoTypes enthalten keine Objekte in Bildern.

    So entfernen Sie Standard-infoTypes aus einem Bild:

    1. Codieren Sie das Bild als Base64-String.

      Wenn Sie eine der Clientbibliotheken für den Schutz sensibler Daten für diese Aufgabe verwenden möchten, überspringen Sie diesen Schritt.

    2. Senden Sie eine Anfrage an die Methode image.redact.

      Wenn Sie Standard-infoTypes entfernen möchten, ist in der Anfrage nur das base64-codierte Bild erforderlich.

    Betrachten Sie beispielsweise das folgende Bild eines Dokuments.

    Originalbild ohne entfernte Daten, das die Kontaktdaten eines Kunden enthält.
    Originalbild ohne entfernte Daten (zum Vergrößern klicken)

    Senden Sie die folgende Anfrage an die Methode image.redact der DLP API, um die Standard-infoTypes aus diesem Bild zu entfernen:

    C#

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Dlp.V2;
    using Google.Protobuf;
    using System;
    using System.IO;
    
    public class RedactSensitiveDataFromImageUsingDefaultInfoTypes
    {
        public static RedactImageResponse RedactImage(
            string projectId,
            string originalImagePath,
            string redactedImagePath)
        {
            // Instantiate the dlp client.
            var dlp = DlpServiceClient.Create();
    
            // Construct the content item.
            var byteContentItem = new ByteContentItem
            {
                Type = ByteContentItem.Types.BytesType.ImagePng,
                Data = ByteString.FromStream(new FileStream(originalImagePath, FileMode.Open))
            };
    
            // Construct the Redact request to be sent by the client. Do not specify the type of info to redact.
            var request = new RedactImageRequest
            {
                ParentAsLocationName = new LocationName(projectId, "global"),
                ByteItem = byteContentItem
            };
    
            // Call the API.
            var response = dlp.RedactImage(request);
    
            // Inspect the response.
            Console.WriteLine($"Redacted image written to: {redactedImagePath}");
    
            // Writes redacted image into file
            response.RedactedImage.WriteTo(new FileStream(redactedImagePath, FileMode.Create, FileAccess.Write));
    
            return response;
        }
    }
    

    Go

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    import (
    	"context"
    	"fmt"
    	"io"
    	"os"
    
    	dlp "cloud.google.com/go/dlp/apiv2"
    	"cloud.google.com/go/dlp/apiv2/dlppb"
    )
    
    // redactImageFileAllInfoTypes redact sensitive data from an image using default infoTypes.
    func redactImageFileAllInfoTypes(w io.Writer, projectID, inputPath, outputPath string) error {
    	// projectId := "my-project-id"
    	// inputPath := "testdata/image.jpg"
    	// outputPath := "testdata/test-output-image-file-all-infoType.jpeg"
    
    	ctx := context.Background()
    
    	// Initialize a client once and reuse it to send multiple requests. Clients
    	// are safe to use across goroutines. When the client is no longer needed,
    	// call the Close method to cleanup its resources.
    	client, err := dlp.NewClient(ctx)
    	if err != nil {
    		return err
    	}
    
    	// Closing the client safely cleans up background resources.
    	defer client.Close()
    
    	// Read the image file.
    	fileBytes, err := os.ReadFile(inputPath)
    	if err != nil {
    		fmt.Fprintf(w, "os.ReadFile: %v", err)
    		return err
    	}
    
    	// Specify the content to be redacted.
    	byteItem := &dlppb.ByteContentItem{
    		Type: dlppb.ByteContentItem_IMAGE_JPEG,
    		Data: fileBytes,
    	}
    
    	// Construct the Redact request to be sent by the client.
    	// Do not specify the type of info to redact.
    	req := &dlppb.RedactImageRequest{
    		Parent:   fmt.Sprintf("projects/%s/locations/global", projectID),
    		ByteItem: byteItem,
    	}
    
    	// Send the request.
    	resp, err := client.RedactImage(ctx, req)
    	if err != nil {
    		return err
    	}
    
    	// Write the output file.
    	if err := os.WriteFile(outputPath, resp.GetRedactedImage(), 0644); err != nil {
    		return err
    	}
    	fmt.Fprintf(w, "Wrote output to %s", outputPath)
    	return nil
    }
    

    Java

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    
    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);
        }
      }
    }

    Node.js

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    // 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 local path to save the resulting image to.
    // const outputPath = 'result.png';
    
    async function redactImage() {
      // Specify the content to be redacted.
      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 the Redact request to be sent by the client.
      // Do not specify the type of info to redact.
      const request = {
        parent: `projects/${projectId}/locations/global`,
        byteItem: {
          type: fileTypeConstant,
          data: fileBytes,
        },
      };
    
      // Use the client to send the API request.
      const [response] = await dlp.redactImage(request);
    
      // Parse the response and process results.
      const image = response.redactedImage;
      fs.writeFileSync(outputPath, image);
      console.log(`Saved image redaction results to path: ${outputPath}`);
    }
    redactImage();

    PHP

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    use Google\Cloud\Dlp\V2\ByteContentItem;
    use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
    use Google\Cloud\Dlp\V2\RedactImageRequest;
    
    /**
     * Redact sensitive data from an image using default infoTypes.
     *
     * @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_all_infotypes(
        // TODO(developer): Replace sample parameters before running the code.
        string $callingProjectId,
        string $imagePath = './test/data/test.png',
        string $outputPath = './test/data/redact_image_all_infotypes.png'
    ): void {
        // Instantiate a client.
        $dlp = new DlpServiceClient();
    
        // 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);
    
        $parent = "projects/$callingProjectId/locations/global";
    
        // Run request.
        $redactImageRequest = (new RedactImageRequest())
            ->setParent($parent)
            ->setByteItem($byteContent);
        $response = $dlp->redactImage($redactImageRequest);
    
        // Save result to file.
        file_put_contents($outputPath, $response->getRedactedImage());
    
        // Print completion message.
        printf('Redacted image saved to %s ' . PHP_EOL, $outputPath);
    }

    Python

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    import google.cloud.dlp
    
    
    def redact_image_all_info_types(
        project: str,
        filename: str,
        output_filename: str,
    ) -> 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.
                A full list of info type categories can be fetched from the API.
        Returns:
            None; the response from the API is printed to the terminal.
        """
    
        # Instantiate a client.
        dlp = google.cloud.dlp_v2.DlpServiceClient()
    
        # 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,
                "byte_item": byte_item,
            }
        )
    
        # Write out the results.
        with open(output_filename, mode="wb") as f:
            f.write(response.redacted_image)
        print(f"Wrote {len(response.redacted_image)} to {output_filename}")
    
    

    REST

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

    Sensitive Data Protection gibt Folgendes zurück:

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

    Decodieren des base64-codierten Bildes

    Das resultierende Bild sieht so aus:

    Bild mit entfernten Daten, alle infoTypes.
    Bild mit entfernten Daten, alle infoTypes (zum Vergrößern klicken)

    Beachten Sie, dass Sensitive Data Protection nicht nur die handschriftliche Sozialversicherungsnummer, die E-Mail-Adresse und die Telefonnummer maskiert, sondern auch das Jahr entfernt hat. Im nächsten Abschnitt wird gezeigt, wie Sie nur bestimmte infoTypes entfernen.

    Bestimmte infoTypes aus einem Bild entfernen

    Wenn Sie nur bestimmte sensible Daten aus einem Bild entfernen möchten, geben Sie die entsprechenden integrierten infoTypes an.

    Senden Sie eine Anfrage an die Methode image.redact der DLP API, um bestimmte infoTypes aus einem Bild zu entfernen. Die Anfrage muss Folgendes enthalten:

    Betrachten Sie das Originalbild aus dem vorherigen Abschnitt. Wenn Sie nur US-amerikanische Sozialversicherungsnummern, E-Mail-Adressen und Telefonnummern entfernen möchten, senden Sie den folgenden JSON-Code an die Methode image.redact der DLP API:

    C#

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Dlp.V2;
    using Google.Protobuf;
    using System;
    using System.IO;
    
    public class RedactImageWithListedInfotypes
    {
        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;
        }
    }
    

    Go

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    import (
    	"context"
    	"fmt"
    	"io"
    	"os"
    
    	dlp "cloud.google.com/go/dlp/apiv2"
    	"cloud.google.com/go/dlp/apiv2/dlppb"
    )
    
    // redactImageFileListedInfoTypes redacts only certain sensitive
    // data from an image using infoTypes
    func redactImageFileListedInfoTypes(w io.Writer, projectID, inputPath, outputPath string) error {
    	// projectId := "my-project-id"
    	// inputPath := "testdata/image.jpg"
    	// outputPath := "testdata/test-output-image-file-listed-infoTypes-redacted.jpeg"
    
    	ctx := context.Background()
    
    	// Initialize a client once and reuse it to send multiple requests. Clients
    	// are safe to use across goroutines. When the client is no longer needed,
    	// call the Close method to cleanup its resources.
    	client, err := dlp.NewClient(ctx)
    	if err != nil {
    		return err
    	}
    
    	// Closing the client safely cleans up background resources.
    	defer client.Close()
    
    	// read the image file
    	fileBytes, err := os.ReadFile(inputPath)
    	if err != nil {
    		return err
    	}
    
    	// Specify the content to be redacted.
    	byteItem := &dlppb.ByteContentItem{
    		Type: dlppb.ByteContentItem_IMAGE_JPEG,
    		Data: fileBytes,
    	}
    
    	// Specify the types of info necessary to redact.
    	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
    	infoTypes := []*dlppb.InfoType{
    		{Name: "US_SOCIAL_SECURITY_NUMBER"},
    		{Name: "EMAIL_ADDRESS"},
    		{Name: "PHONE_NUMBER"},
    	}
    
    	inspectConfig := &dlppb.InspectConfig{
    		InfoTypes: infoTypes,
    	}
    
    	// Prepare redaction configs.
    	var x []*dlppb.RedactImageRequest_ImageRedactionConfig
    	for _, v := range infoTypes {
    		x = append(x, &dlppb.RedactImageRequest_ImageRedactionConfig{Target: &dlppb.RedactImageRequest_ImageRedactionConfig_InfoType{InfoType: v}})
    	}
    
    	// Construct the Inspect request to be sent by the client.
    	req := &dlppb.RedactImageRequest{
    		Parent:                fmt.Sprintf("projects/%s/locations/global", projectID),
    		ByteItem:              byteItem,
    		ImageRedactionConfigs: x,
    		InspectConfig:         inspectConfig,
    	}
    
    	// Send the request.
    	resp, err := client.RedactImage(ctx, req)
    	if err != nil {
    		return err
    	}
    
    	// Write the output file.
    	if err := os.WriteFile(outputPath, resp.GetRedactedImage(), 0644); err != nil {
    		return err
    	}
    	fmt.Fprintf(w, "Wrote output to %s\n", outputPath)
    	return nil
    }
    

    Java

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    
    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);
        }
      }
    }

    Node.js

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    // 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 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 redactImageWithInfoTypes() {
      // 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: {
          infoTypes: infoTypes,
        },
        imageRedactionConfigs: infoTypes.map(infoType => ({infoType: infoType})),
      };
    
      // 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}`);
    }
    redactImageWithInfoTypes();

    PHP

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    use Google\Cloud\Dlp\V2\ByteContentItem;
    use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
    use Google\Cloud\Dlp\V2\InfoType;
    use Google\Cloud\Dlp\V2\InspectConfig;
    use Google\Cloud\Dlp\V2\RedactImageRequest;
    use Google\Cloud\Dlp\V2\RedactImageRequest\ImageRedactionConfig;
    
    /**
     * Redact only certain sensitive data from an image using infoTypes.
     *
     * @param string $callingProjectId    The project ID to run the API call under.
     * @param string $imagePath           The local filepath of the image to redact.
     * @param string $outputPath          The local filepath to save the resulting image to.
     */
    function redact_image_listed_infotypes(
        // TODO(developer): Replace sample parameters before running the code.
        string $callingProjectId,
        string $imagePath = './test/data/test.png',
        string $outputPath = './test/data/redact_image_listed_infotypes.png'
    ): void {
        // Instantiate a client.
        $dlp = new DlpServiceClient();
    
        // Specify the types of info necessary to redact.
        $infoTypes = [
            (new InfoType())
                ->setName('US_SOCIAL_SECURITY_NUMBER'),
            (new InfoType())
                ->setName('EMAIL_ADDRESS'),
            (new InfoType())
                ->setName('PHONE_NUMBER'),
        ];
    
        // Create the configuration object.
        $inspectConfig = (new InspectConfig())
            ->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.
        $redactImageRequest = (new RedactImageRequest())
            ->setParent($parent)
            ->setInspectConfig($inspectConfig)
            ->setByteItem($byteContent)
            ->setImageRedactionConfigs($imageRedactionConfigs);
        $response = $dlp->redactImage($redactImageRequest);
    
        // Save result to file.
        file_put_contents($outputPath, $response->getRedactedImage());
    
        // Print completion message.
        printf('Redacted image saved to %s' . PHP_EOL, $outputPath);
    }

    Python

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    import mimetypes
    from typing import List, Optional
    
    import google.cloud.dlp
    
    
    def redact_image_listed_info_types(
        project: str,
        filename: str,
        output_filename: str,
        info_types: List[str],
        min_likelihood: Optional[str] = None,
        mime_type: Optional[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.
                A full list of info type categories can be fetched from the API.
            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.
        # https://github.com/googleapis/googleapis/blob/master/google/privacy/dlp/v2/dlp.proto / message ByteContentItem
        supported_content_types = {
            None: 0,  # "Unspecified" or BYTES_TYPE_UNSPECIFIED
            "image/jpeg": 1,  # IMAGE_JPEG
            "image/bmp": 2,  # IMAGE_BMP
            "image/png": 3,  # IMAGE_PNG
            "image/svg": 4,  # IMAGE_SVG - Adjusted to "image/svg+xml" for correct MIME type
            "text/plain": 5,  # TEXT_UTF8
            # Note: No specific MIME type for general "image", mapping to IMAGE for any image type not specified
            "image": 6,  # IMAGE - Any image type
            "application/msword": 7,  # WORD_DOCUMENT
            "application/pdf": 8,  # PDF
            "application/powerpoint": 9,  # POWERPOINT_DOCUMENT
            "application/msexcel": 10,  # EXCEL_DOCUMENT
            "application/avro": 11,  # AVRO
            "text/csv": 12,  # CSV
            "text/tsv": 13,  # TSV
        }
        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(f"Wrote {len(response.redacted_image)} to {output_filename}")
    
    

    REST

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

    Sensitive Data Protection gibt Folgendes zurück:

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

    Decodieren des base64-codierten Bildes

    Das resultierende Bild sieht so aus:

    Bild mit entfernten Daten, drei infoTypes.
    Bild mit entfernten Daten, drei infoTypes (zum Vergrößern klicken)

    Sie können entfernte Informationen nach infoType farblich codieren, wenn Sie auf einen Blick erkennen möchten, was entfernt wurde. Weitere Informationen finden Sie im folgenden Abschnitt.

    infoTypes aus einem Bild mit Farbcodierung entfernen

    Wenn Sie entfernte Informationen nach infoType farblich codieren möchten, kombinieren Sie infoType-Detektoren mit RGB-Farbraumwerten.

    Wenn Sie aus einem Bild entfernte infoTypes farblich codieren möchten, senden Sie eine Anfrage an die Methode image.redact der DLP API. Die Anfrage muss Folgendes enthalten:

    Betrachten Sie das Originalbild aus dem ersten Abschnitt. Wenn Sie die Sozialversicherungsnummern in den USA mit einem lila Feld, E-Mail-Adressen mit einem grünen Feld und Telefonnummern mit einem orangefarbenen Feld entfernen möchten, senden Sie die folgende JSON an die image.redact Methode der DLP API:

    C#

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Dlp.V2;
    using Google.Protobuf;
    using System;
    using System.IO;
    
    public class RedactImageWithColorCodedInfoTypes
    {
        public static RedactImageResponse RedactImage(
            string projectId,
            string originalImagePath,
            string redactedImagePath)
        {
            // Instantiate the dlp client.
            var dlp = DlpServiceClient.Create();
    
            // Construct the content item by providing the image and its type.
            var byteContentItem = new ByteContentItem
            {
                Type = ByteContentItem.Types.BytesType.ImagePng,
                Data = ByteString.FromStream(new FileStream(originalImagePath, FileMode.Open))
            };
    
            // Define types of info and associate each one with a different color to redact config.
            var ssnRedactionConfig = new RedactImageRequest.Types.ImageRedactionConfig
            {
                InfoType = new InfoType { Name = "US_SOCIAL_SECURITY_NUMBER" },
                RedactionColor = new Color
                {
                    Red = 0.3f,
                    Green = 0.1f,
                    Blue = 0.6f
                }
            };
    
            var emailRedactionConfig = new RedactImageRequest.Types.ImageRedactionConfig
            {
                InfoType = new InfoType { Name = "EMAIL_ADDRESS" },
                RedactionColor = new Color
                {
                    Red = 0.5f,
                    Green = 0.5f,
                    Blue = 1f
                }
            };
    
            var phoneRedactionConfig = new RedactImageRequest.Types.ImageRedactionConfig
            {
                InfoType = new InfoType { Name = "PHONE_NUMBER" },
                RedactionColor = new Color
                {
                    Red = 1f,
                    Green = 0f,
                    Blue = 0.6f
                }
            };
    
            // Construct the Redact request to be sent by the client. Do not specify the type of info to redact.
            var request = new RedactImageRequest
            {
                ParentAsLocationName = new LocationName(projectId, "global"),
                ImageRedactionConfigs = { ssnRedactionConfig, emailRedactionConfig, phoneRedactionConfig },
                ByteItem = byteContentItem
            };
    
            // Call the API.
            RedactImageResponse response = dlp.RedactImage(request);
    
            // Writes redacted image into file
            response.RedactedImage.WriteTo(new FileStream(redactedImagePath, FileMode.Create, FileAccess.Write));
    
            Console.WriteLine($"Redacted image written to: {redactedImagePath}");
    
            return response;
        }
    }
    

    Go

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    import (
    	"context"
    	"fmt"
    	"io"
    	"os"
    
    	dlp "cloud.google.com/go/dlp/apiv2"
    	"cloud.google.com/go/dlp/apiv2/dlppb"
    )
    
    // redactImageFileColoredInfoTypes redacts data from an image with color-coded infoTypes.
    func redactImageFileColoredInfoTypes(w io.Writer, projectID, inputPath, outputPath string) error {
    	// projectId := "my-project-id"
    	// inputPath := "testdata/image.jpg"
    	// outputPath := "testdata/test-output-image-file-colored-infoType.jpeg"
    
    	ctx := context.Background()
    
    	// Initialize a client once and reuse it to send multiple requests. Clients
    	// are safe to use across goroutines. When the client is no longer needed,
    	// call the Close method to cleanup its resources.
    	client, err := dlp.NewClient(ctx)
    	if err != nil {
    		return err
    	}
    
    	// Closing the client safely cleans up background resources.
    	defer client.Close()
    
    	// read the image file
    	fileBytes, err := os.ReadFile(inputPath)
    	if err != nil {
    		return err
    	}
    
    	// Specify the content to be redacted.
    	byteItem := &dlppb.ByteContentItem{
    		Type: dlppb.ByteContentItem_IMAGE_JPEG,
    		Data: fileBytes,
    	}
    
    	// 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.
    
    	ssnRedactionConfig := &dlppb.RedactImageRequest_ImageRedactionConfig{
    		Target: &dlppb.RedactImageRequest_ImageRedactionConfig_InfoType{
    			InfoType: &dlppb.InfoType{
    				Name: "US_SOCIAL_SECURITY_NUMBER",
    			},
    		},
    		RedactionColor: &dlppb.Color{
    			Red:   0.3,
    			Green: 0.1,
    			Blue:  0.6,
    		},
    	}
    
    	emailRedactionConfig := &dlppb.RedactImageRequest_ImageRedactionConfig{
    		Target: &dlppb.RedactImageRequest_ImageRedactionConfig_InfoType{
    			InfoType: &dlppb.InfoType{
    				Name: "EMAIL_ADDRESS",
    			},
    		},
    		RedactionColor: &dlppb.Color{
    			Red:   0.5,
    			Green: 0.5,
    			Blue:  1,
    		},
    	}
    
    	phoneRedactionConfig := &dlppb.RedactImageRequest_ImageRedactionConfig{
    		Target: &dlppb.RedactImageRequest_ImageRedactionConfig_InfoType{
    			InfoType: &dlppb.InfoType{
    				Name: "PHONE_NUMBER",
    			},
    		},
    		RedactionColor: &dlppb.Color{
    			Red:   1,
    			Green: 0,
    			Blue:  0.6,
    		},
    	}
    
    	// Construct the Inspect request to be sent by the client.
    	req := &dlppb.RedactImageRequest{
    		Parent:   fmt.Sprintf("projects/%s/locations/global", projectID),
    		ByteItem: byteItem,
    		ImageRedactionConfigs: []*dlppb.RedactImageRequest_ImageRedactionConfig{
    			emailRedactionConfig,
    			phoneRedactionConfig,
    			ssnRedactionConfig,
    		},
    	}
    
    	// Send the request.
    	resp, err := client.RedactImage(ctx, req)
    	if err != nil {
    		return err
    	}
    
    	// Write the output file.
    	if err := os.WriteFile(outputPath, resp.GetRedactedImage(), 0644); err != nil {
    		return err
    	}
    
    	fmt.Fprintf(w, "Wrote output to %s", outputPath)
    	return nil
    }
    

    Java

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    
    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);
        }
      }
    }

    Node.js

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    // 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 local path to save the resulting image to.
    // const outputPath = 'result.png';
    
    async function redactImageColoredInfoType() {
      // Define types of info to redact associate each one with a different color.
      const 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, green: 0.5, blue: 1},
        },
        {
          infoType: {name: 'PHONE_NUMBER'},
          redactionColor: {red: 1, green: 0, blue: 0.6},
        },
      ];
    
      // 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 the Redact request to be sent by the client.
      const request = {
        parent: `projects/${projectId}/locations/global`,
        byteItem: {
          type: fileTypeConstant,
          data: fileBytes,
        },
        imageRedactionConfigs: imageRedactionConfigs,
      };
    
      // Send the request and receive response from the service.
      const [response] = await dlp.redactImage(request);
      const image = response.redactedImage;
      fs.writeFileSync(outputPath, image);
      console.log(`Saved image redaction results to path: ${outputPath}`);
    }
    redactImageColoredInfoType();

    PHP

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    use Google\Cloud\Dlp\V2\ByteContentItem;
    use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
    use Google\Cloud\Dlp\V2\Color;
    use Google\Cloud\Dlp\V2\InfoType;
    use Google\Cloud\Dlp\V2\InspectConfig;
    use Google\Cloud\Dlp\V2\RedactImageRequest;
    use Google\Cloud\Dlp\V2\RedactImageRequest\ImageRedactionConfig;
    
    /**
     * Redact data from an image with color-coded infoTypes.
     *
     * @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_colored_infotypes(
        // TODO(developer): Replace sample parameters before running the code.
        string $callingProjectId,
        string $imagePath = './test/data/test.png',
        string $outputPath = './test/data/sensitive-data-image-redacted-color-coding.png'
    ): void {
        // Instantiate a client.
        $dlp = new DlpServiceClient();
    
        // 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);
    
        // Define the types of information to redact and associate each one with a different color.
        $ssnInfotype = (new InfoType())
            ->setName('US_SOCIAL_SECURITY_NUMBER');
        $emailInfotype = (new InfoType())
            ->setName('EMAIL_ADDRESS');
        $phoneInfotype = (new InfoType())
            ->setName('PHONE_NUMBER');
        $infotypes = [$ssnInfotype, $emailInfotype, $phoneInfotype];
    
        $ssnRedactionConfig = (new ImageRedactionConfig())
            ->setInfoType($ssnInfotype)
            ->setRedactionColor((new Color())
                ->setRed(.3)
                ->setGreen(.1)
                ->setBlue(.6));
    
        $emailRedactionConfig = (new ImageRedactionConfig())
            ->setInfoType($emailInfotype)
            ->setRedactionColor((new Color())
                ->setRed(.5)
                ->setGreen(.5)
                ->setBlue(1));
    
        $phoneRedactionConfig = (new ImageRedactionConfig())
            ->setInfoType($phoneInfotype)
            ->setRedactionColor((new Color())
                ->setRed(1)
                ->setGreen(0)
                ->setBlue(.6));
    
        $imageRedactionConfigs = [$ssnRedactionConfig, $emailRedactionConfig, $phoneRedactionConfig];
    
        // Create the configuration object.
        $inspectConfig = (new InspectConfig())
            ->setInfoTypes($infotypes);
        $parent = "projects/$callingProjectId/locations/global";
    
        // Run request.
        $redactImageRequest = (new RedactImageRequest())
            ->setParent($parent)
            ->setByteItem($byteContent)
            ->setInspectConfig($inspectConfig)
            ->setImageRedactionConfigs($imageRedactionConfigs);
        $response = $dlp->redactImage($redactImageRequest);
    
        // Save result to file.
        file_put_contents($outputPath, $response->getRedactedImage());
    
        // Print completion message.
        printf('Redacted image saved to %s ' . PHP_EOL, $outputPath);
    }

    Python

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    import google.cloud.dlp
    
    
    def redact_image_with_colored_info_types(
        project: str,
        filename: str,
        output_filename: str,
    ) -> None:
        """Uses the Data Loss Prevention API to redact protected data in an image by
        color coding the infoTypes.
           Args:
               project: The Google Cloud project id to use as a parent resource.
               filename: The path of the image file to inspect.
               output_filename: The path to which the redacted image will be written.
        """
    
        # Instantiate a client.
        dlp = google.cloud.dlp_v2.DlpServiceClient()
    
        # Prepare image_redaction_configs, a list of dictionaries. Each dictionary
        # contains an infoType and the color used for the replacement.
    
        ssn_redaction_config = {
            "info_type": {"name": "US_SOCIAL_SECURITY_NUMBER"},
            "redaction_color": {
                "red": 0.3,
                "green": 0.1,
                "blue": 0.6,
            },
        }
    
        email_redaction_config = {
            "info_type": {"name": "EMAIL_ADDRESS"},
            "redaction_color": {
                "red": 0.5,
                "green": 0.5,
                "blue": 1.0,
            },
        }
    
        phone_redaction_config = {
            "info_type": {"name": "PHONE_NUMBER"},
            "redaction_color": {
                "red": 1.0,
                "green": 0.0,
                "blue": 0.6,
            },
        }
    
        image_redaction_configs = [
            ssn_redaction_config,
            email_redaction_config,
            phone_redaction_config,
        ]
    
        # Construct the configuration dictionary.
        inspect_config = {"info_types": [_i["info_type"] for _i in image_redaction_configs]}
    
        # Construct the byte_item, containing the file's byte data.
        with open(filename, mode="rb") as f:
            byte_item = {"type_": "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,
                "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)
    
        byte_count = len(response.redacted_image)
        print(f"Wrote {byte_count} to {output_filename}")
    
    

    REST

        {
          "byteItem": {
            "data": "[BASE64-ENCODED-IMAGE]",
            "type": "IMAGE_PNG"
          },
          "imageRedactionConfigs": [
            {
              "infoType": {
                "name": "PERSON_NAME"
              },
              "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
              }
            }
          ]
        }

    Sensitive Data Protection gibt Folgendes zurück:

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

    Decodieren des base64-codierten Bildes

    Das resultierende Bild sieht so aus:

    Bild mit entfernten Daten, drei farbcodierte infoTypes.
    Bild mit entfernten Daten, drei farbcodierte infoTypes (zum Vergrößern klicken)

    Gesamten Text aus einem Bild entfernen

    Sensitive Data Protection enthält auch eine Option zum Entfernen des gesamten erkannten Texts in einem Bild.

    Senden Sie eine Anfrage an die Methode image.redact der DLP API, um den gesamten Text aus einem Bild zu entfernen. Die Anfrage muss Folgendes enthalten:

    • Das Bild.
    • Die Option redactAllText, die auf true festgelegt ist.

    Betrachten Sie das Originalbild aus dem ersten Abschnitt. Senden Sie den folgenden JSON-Code an die Methode image.redact der DLP API, um den gesamten Text zu entfernen:

    C#

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Dlp.V2;
    using Google.Protobuf;
    using System;
    using System.IO;
    
    public class RedactDetectedTextInImage
    {
        public static RedactImageResponse RedactTextImage(
            string projectId,
            string originalImagePath,
            string redactedImagePath)
        {
            // Instantiate the dlp client.
            var dlp = DlpServiceClient.Create();
    
            // Construct the content item by specifying the content to be redacted.
            var byteContentItem = new ByteContentItem
            {
                Type = ByteContentItem.Types.BytesType.ImagePng,
                Data = ByteString.FromStream(new FileStream(originalImagePath, FileMode.Open))
            };
    
            // Enable redaction of all text.
            var imageRedactionConfig = new RedactImageRequest.Types.ImageRedactionConfig
            {
                RedactAllText = true
            };
    
            // Construct the Redact request to be sent by the client. Do not specify the type of info to redact.
            var request = new RedactImageRequest
            {
                ParentAsLocationName = new LocationName(projectId, "global"),
                ImageRedactionConfigs = { imageRedactionConfig },
                ByteItem = byteContentItem
            };
    
            // Call the API.
            var response = dlp.RedactImage(request);
    
            // Inspect the response.
            Console.WriteLine($"Redacted image written to: {redactedImagePath}");
    
            // Writes redacted image into file
            response.RedactedImage.WriteTo(new FileStream(redactedImagePath, FileMode.Create, FileAccess.Write));
    
            return response;
        }
    }
    

    Go

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    import (
    	"context"
    	"fmt"
    	"io"
    	"os"
    
    	dlp "cloud.google.com/go/dlp/apiv2"
    	"cloud.google.com/go/dlp/apiv2/dlppb"
    )
    
    // redactImageFileAllText redacts all detected text in an image
    func redactImageFileAllText(w io.Writer, projectID, inputPath, outputPath string) error {
    	// projectId := "my-project-id"
    	// inputPath := "testdata/image.jpg"
    	// outputPath := "testdata/test-output-image-file-all-text.jpeg"
    	ctx := context.Background()
    
    	// Initialize a client once and reuse it to send multiple requests. Clients
    	// are safe to use across goroutines. When the client is no longer needed,
    	// call the Close method to cleanup its resources.
    	client, err := dlp.NewClient(ctx)
    	if err != nil {
    		return err
    	}
    
    	// Closing the client safely cleans up background resources.
    	defer client.Close()
    
    	// read the image file
    	fileBytes, err := os.ReadFile(inputPath)
    	if err != nil {
    		return err
    	}
    
    	// Specify the content to be redacted.
    	byteItem := &dlppb.ByteContentItem{
    		Type: dlppb.ByteContentItem_IMAGE_JPEG,
    		Data: fileBytes,
    	}
    
    	// Enable redaction of all text.
    	imageRedactConfig := &dlppb.RedactImageRequest_ImageRedactionConfig{
    		Target: &dlppb.RedactImageRequest_ImageRedactionConfig_RedactAllText{
    			RedactAllText: true,
    		},
    	}
    
    	// Construct the Redact request to be sent by the client.
    	// Do not specify the type of info to redact.
    	req := &dlppb.RedactImageRequest{
    		Parent:   fmt.Sprintf("projects/%s/locations/global", projectID),
    		ByteItem: byteItem,
    		ImageRedactionConfigs: []*dlppb.RedactImageRequest_ImageRedactionConfig{
    			imageRedactConfig,
    		},
    	}
    
    	// Send the request.
    	resp, err := client.RedactImage(ctx, req)
    	if err != nil {
    		return err
    	}
    
    	// Write the output file.
    	if err := os.WriteFile(outputPath, resp.GetRedactedImage(), 0644); err != nil {
    		return err
    	}
    	fmt.Fprintf(w, "Wrote output to %s", outputPath)
    	return nil
    
    }
    

    Java

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    
    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);
        }
      }
    }

    Node.js

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    // 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 local path to save the resulting image to.
    // const outputPath = 'result.png';
    
    async function redactImageAllText() {
      // Enable redaction of all text.
      const imageRedactionConfigs = [{redactAllText: true}];
    
      // 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 the Redact request to be sent by the client.
      // Do not specify the type of info to redact.
      const request = {
        parent: `projects/${projectId}/locations/global`,
        byteItem: {
          type: fileTypeConstant,
          data: fileBytes,
        },
        imageRedactionConfigs: imageRedactionConfigs,
      };
    
      // Run image redaction request
      const [response] = await dlp.redactImage(request);
    
      // Parse the response and process results.
      const image = response.redactedImage;
      fs.writeFileSync(outputPath, image);
      console.log(`Saved image redaction results to path: ${outputPath}`);
    }
    redactImageAllText();

    PHP

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    use Google\Cloud\Dlp\V2\ByteContentItem;
    use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
    use Google\Cloud\Dlp\V2\RedactImageRequest;
    use Google\Cloud\Dlp\V2\RedactImageRequest\ImageRedactionConfig;
    
    /**
     * Redact all detected text in an image.
     *
     * @param string $callingProjectId    The project ID to run the API call under.
     * @param string $imagePath           The local filepath of the image to redact.
     * @param string $outputPath          The local filepath to save the resulting image to.
     */
    function redact_image_all_text(
        // TODO(developer): Replace sample parameters before running the code.
        string $callingProjectId,
        string $imagePath = './test/data/test.png',
        string $outputPath = './test/data/redact_image_all_text.png'
    ): void {
        // Instantiate a client.
        $dlp = new DlpServiceClient();
    
        // 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);
    
        // Enable redaction of all text.
        $imageRedactionConfig = (new ImageRedactionConfig())
            ->setRedactAllText(true);
    
        $parent = "projects/$callingProjectId/locations/global";
    
        // Run request.
        $redactImageRequest = (new RedactImageRequest())
            ->setParent($parent)
            ->setByteItem($byteContent)
            ->setImageRedactionConfigs([$imageRedactionConfig]);
        $response = $dlp->redactImage($redactImageRequest);
    
        // Save result to file.
        file_put_contents($outputPath, $response->getRedactedImage());
    
        // Print completion message.
        printf('Redacted image saved to %s' . PHP_EOL, $outputPath);
    }

    Python

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    import google.cloud.dlp
    
    
    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
            )
        )
    
    

    REST

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

    Sensitive Data Protection gibt Folgendes zurück:

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

    Decodieren des base64-codierten Bildes

    Die API gibt dieselben Bilder zurück, die Sie angegeben haben. Aber Text, der gemäß Ihren Kriterien als vertrauliche Informationen erkannt wurde, wurde entfernt.

    Das resultierende Bild sieht so aus:

    Bild mit entfernten Daten, gesamter Text.
    Geschwärztes Bild, gesamter Text (zum Vergrößern klicken).

    Codebeispiel mit Wahrscheinlichkeitseinstellung

    Dieses Beispiel ähnelt dem Beispiel unter Bestimmte infoTypes aus einem Bild entfernen. Außerdem wird gezeigt, wie Sie eine Mindestwahrscheinlichkeit angeben.

    C#

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    
    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,
                    IncludeQuote = true,
                    InfoTypes =
                    {
                        new InfoType { Name = "PHONE_NUMBER" },
                        new InfoType { Name = "EMAIL_ADDRESS" },
                        new InfoType { Name = "CREDIT_CARD_NUMBER" }
                    }
                },
                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;
        }
    }
    

    Go

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    import (
    	"context"
    	"fmt"
    	"io"
    	"os"
    
    	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 := os.ReadFile(inputPath)
    	if err != nil {
    		return fmt.Errorf("os.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 := os.WriteFile(outputPath, resp.GetRedactedImage(), 0644); err != nil {
    		return fmt.Errorf("os.WriteFile: %w", err)
    	}
    	fmt.Fprintf(w, "Wrote output to %s", outputPath)
    	return nil
    }
    

    Java

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    
    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.Likelihood;
    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;
    import java.util.ArrayList;
    import java.util.List;
    
    class RedactImageFile {
    
      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";
        redactImageFile(projectId, inputPath, outputPath);
      }
    
      static void redactImageFile(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 inspected.
          ByteString fileBytes = ByteString.readFrom(new FileInputStream(inputPath));
          ByteContentItem byteItem =
              ByteContentItem.newBuilder().setType(BytesType.IMAGE).setData(fileBytes).build();
    
          // Specify the type of info and likelihood 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[] {"PHONE_NUMBER", "EMAIL_ADDRESS", "CREDIT_CARD_NUMBER"}) {
            infoTypes.add(InfoType.newBuilder().setName(typeName).build());
          }
          InspectConfig config =
              InspectConfig.newBuilder()
                  .addAllInfoTypes(infoTypes)
                  .setMinLikelihood(Likelihood.LIKELY)
                  .build();
    
          // Construct the Redact request to be sent by the client.
          RedactImageRequest request =
              RedactImageRequest.newBuilder()
                  .setParent(LocationName.of(projectId, "global").toString())
                  .setByteItem(byteItem)
                  .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);
        }
      }
    }

    Node.js

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    // 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();

    PHP

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    use Google\Cloud\Dlp\V2\ByteContentItem;
    use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
    use Google\Cloud\Dlp\V2\InfoType;
    use Google\Cloud\Dlp\V2\InspectConfig;
    use Google\Cloud\Dlp\V2\Likelihood;
    use Google\Cloud\Dlp\V2\RedactImageRequest;
    use Google\Cloud\Dlp\V2\RedactImageRequest\ImageRedactionConfig;
    
    /**
     * 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
        $redactImageRequest = (new RedactImageRequest())
            ->setParent($parent)
            ->setInspectConfig($inspectConfig)
            ->setByteItem($byteContent)
            ->setImageRedactionConfigs($imageRedactionConfigs);
        $response = $dlp->redactImage($redactImageRequest);
    
        // Save result to file
        file_put_contents($outputPath, $response->getRedactedImage());
    
        // Print completion message
        print('Redacted image saved to ' . $outputPath . PHP_EOL);
    }

    Python

    Informationen zum Installieren und Verwenden der Clientbibliothek für Sensitive Data Protection finden Sie unter Sensitive Data Protection-Clientbibliotheken.

    Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Sensitive Data Protection zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

    import mimetypes
    from typing import List
    
    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.
        # https://github.com/googleapis/googleapis/blob/master/google/privacy/dlp/v2/dlp.proto / message ByteContentItem
        supported_content_types = {
            None: 0,  # "Unspecified" or BYTES_TYPE_UNSPECIFIED
            "image/jpeg": 1,  # IMAGE_JPEG
            "image/bmp": 2,  # IMAGE_BMP
            "image/png": 3,  # IMAGE_PNG
            "image/svg": 4,  # IMAGE_SVG - Adjusted to "image/svg+xml" for correct MIME type
            "text/plain": 5,  # TEXT_UTF8
            # Note: No specific MIME type for general "image", mapping to IMAGE for any image type not specified
            "image": 6,  # IMAGE - Any image type
            "application/msword": 7,  # WORD_DOCUMENT
            "application/pdf": 8,  # PDF
            "application/powerpoint": 9,  # POWERPOINT_DOCUMENT
            "application/msexcel": 10,  # EXCEL_DOCUMENT
            "application/avro": 11,  # AVRO
            "text/csv": 12,  # CSV
            "text/tsv": 13,  # TSV
        }
        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
            )
        )
    
    

    Testen

    Sie können jedes der Beispiele auf dieser Seite selbst im APIs Explorer auf der Referenzseite für image.redact ausprobieren. Sie können auch mit Ihren eigenen Bildern experimentieren:

    Zu APIs Explorer

    Nächste Schritte