Redact sensitive data from an image (v2)

Redact sensitive information, such as email addresses, from an image.

Code sample

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.InfoType;
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.IOException;
import java.util.Arrays;
import java.util.Base64;

public class RedactImage {

  public static void main(String[] args) throws IOException {
    String projectId = "example-project-id";
    String locationId = "example-location-id";
    redactImage(projectId, locationId);
  }

  public static void redactImage(String projectId, String locationId) throws IOException {
    try (DlpServiceClient client = DlpServiceClient.create()) {
      // Decode a minimal valid 1x1 PNG image
      byte[] imageBytes =
          Base64.getDecoder()
              .decode(
                  "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==");

      ByteContentItem byteItem =
          ByteContentItem.newBuilder()
              .setType(BytesType.IMAGE_PNG)
              .setData(ByteString.copyFrom(imageBytes))
              .build();

      ImageRedactionConfig[] imageRedactionConfigs =
          new ImageRedactionConfig[] {
            ImageRedactionConfig.newBuilder()
                .setInfoType(InfoType.newBuilder().setName("EMAIL_ADDRESS").build())
                .build()
          };

      RedactImageRequest request =
          RedactImageRequest.newBuilder()
              .setParent(LocationName.of(projectId, locationId).toString())
              .setByteItem(byteItem)
              .addAllImageRedactionConfigs(Arrays.asList(imageRedactionConfigs))
              .build();

      RedactImageResponse response = client.redactImage(request);
      System.out.println("Redacted image size: " + response.getRedactedImage().size() + " bytes");
    }
  }
}

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.

'use strict';

const {DlpServiceClient} = require('@google-cloud/dlp');
const {status} = require('@grpc/grpc-js');

const client = new DlpServiceClient();

/**
 * Use the redactImage method
 *
 * @param {string} projectId - The Google Cloud project ID.
 */
async function redactImage(projectId) {
  try {
    const parent = `projects/${projectId}`;

    // Construct image payload with 1x1 PNG test byte data
    const byteItem = {
      type: 'IMAGE_PNG',
      data: Buffer.from(
        'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
        'base64'
      ),
    };

    // Configure redaction masks for identified sensitive info types
    const imageRedactionConfigs = [
      {
        infoType: {name: 'EMAIL_ADDRESS'},
        redactionColor: {red: 0, green: 0, blue: 0},
      },
    ];

    // Configure info types to scan without specifying finding limits
    const inspectConfig = {
      infoTypes: [{name: 'EMAIL_ADDRESS'}, {name: 'PHONE_NUMBER'}],
      minLikelihood: 'LIKELIHOOD_UNSPECIFIED',
    };

    const request = {
      parent,
      byteItem,
      imageRedactionConfigs,
      inspectConfig,
    };

    const [response] = await client.redactImage(request);

    console.log(`Redacted image size: ${response.redactedImage.length} bytes`);
    if (response.inspectResult && response.inspectResult.findings) {
      console.log(`Identified findings count: ${response.inspectResult.findings.length}`);
    }
  } catch (err) {
    if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument provided: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code === status.NOT_FOUND) {
      console.error(`Resource not found: ${err.message}`);
    } else {
      console.error(`DLP request failed with error code ${err.code}: ${err.message}`);
    }
  }
}

module.exports = { redactImage };

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 struct
import zlib

import google.api_core.exceptions
from google.cloud import dlp_v2


def redact_image(project_id: str) -> None:
    """Redacts sensitive data from an image.

    Args:
        project_id: The Google Cloud project ID to use for the redaction request.
    """
    client = dlp_v2.DlpServiceClient()

    # Construct a valid 100x100 RGB PNG image in memory for demonstration.
    width, height = 100, 100
    raw_scanlines = b"".join(
        b"\x00" + b"\xff\xff\xff" * width for _ in range(height)
    )
    compressed_stream = zlib.compress(raw_scanlines)
    ihdr_payload = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
    ihdr_checksum = struct.pack(">I", zlib.crc32(b"IHDR" + ihdr_payload))
    idat_checksum = struct.pack(">I", zlib.crc32(b"IDAT" + compressed_stream))
    iend_checksum = struct.pack(">I", zlib.crc32(b"IEND"))

    sample_png_bytes = (
        b"\x89PNG\r\n\x1a\n"
        + struct.pack(">I", len(ihdr_payload))
        + b"IHDR"
        + ihdr_payload
        + ihdr_checksum
        + struct.pack(">I", len(compressed_stream))
        + b"IDAT"
        + compressed_stream
        + idat_checksum
        + struct.pack(">I", 0)
        + b"IEND"
        + iend_checksum
    )

    byte_item = dlp_v2.ByteContentItem(
        type_=dlp_v2.ByteContentItem.BytesType.IMAGE_PNG,
        data=sample_png_bytes,
    )
    image_redaction_configs = [
        dlp_v2.RedactImageRequest.ImageRedactionConfig(
            info_type=dlp_v2.InfoType(name="EMAIL_ADDRESS")
        )
    ]
    inspect_config = dlp_v2.InspectConfig(
        info_types=[dlp_v2.InfoType(name="EMAIL_ADDRESS")],
        min_likelihood=dlp_v2.Likelihood.POSSIBLE,
    )

    parent = f"projects/{project_id}"
    request = dlp_v2.RedactImageRequest(
        parent=parent,
        byte_item=byte_item,
        image_redaction_configs=image_redaction_configs,
        inspect_config=inspect_config,
        include_findings=True,
    )

    try:
        response = client.redact_image(request=request)
        print(f"Redacted image size in bytes: {len(response.redacted_image)}")
        if response.inspect_result:
            print(
                f"Identified findings count: {len(response.inspect_result.findings)}"
            )
    except google.api_core.exceptions.GoogleAPICallError as error:
        print(f"Error during image redaction: {error.message}")

What's next

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