Redact all detected text in an image

Redact all detected text in an image.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

	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 := ioutil.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 := ioutil.WriteFile(outputPath, resp.GetRedactedImage(), 0644); err != nil {
		return err
	}
	fmt.Fprintf(w, "Wrote output to %s", outputPath)
	return nil

}

Java

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// 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

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.