Cloud Data Loss Prevention (Cloud DLP) is now a part of Sensitive Data Protection. The API name remains the same: Cloud Data Loss Prevention API (DLP API). For information about the services that make up Sensitive Data Protection, see Sensitive Data Protection overview.
Inspect images for sensitive data
Stay organized with collections
Save and categorize content based on your preferences.
This document describes how to use the Cloud Data Loss Prevention API to detect sensitive text and
objects in an image. Sensitive Data Protection returns the
location of any sensitive data that it detects.
Given an image as input, Sensitive Data Protection detects sensitive data
in the image. The output of an inspection operation includes the detected
infoTypes, the
likelihood of the match, and pixel
coordinates and length values that indicate the areas within which
Sensitive Data Protection found the sensitive data. The coordinates at the bottom
left corner of an image are (0,0).
Inspect an image for all default infoTypes
To inspect an image for sensitive data, you submit a base64-encoded image to the
content.inspect
method. If you don't specify specific information types (infoTypes)
to search for, Sensitive Data Protection
searches for the most common infoTypes.
To inspect an image for all default infoTypes, follow these steps:
Encode the image as base64.
Submit a request to the content.inspect method of the DLP API.
The request requires only the base64-encoded image.
import("context""fmt""io""os"dlp"cloud.google.com/go/dlp/apiv2""cloud.google.com/go/dlp/apiv2/dlppb")// inspectImageFileAllInfoTypes inspects a image for sensitive data with infoTypesfuncinspectImageFileAllInfoTypes(wio.Writer,projectID,inputPathstring)error{// projectId := "your-project-id"// inputPath := "your-input-path"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)iferr!=nil{returnerr}// Closing the client safely cleans up background resources.deferclient.Close()// read the image filedata,err:=os.ReadFile(inputPath)iferr!=nil{returnerr}// Create and send the request.req:=&dlppb.InspectContentRequest{Parent:fmt.Sprintf("projects/%s/locations/global",projectID),Item:&dlppb.ContentItem{// Specify the content to be inspected.DataItem:&dlppb.ContentItem_ByteItem{ByteItem:&dlppb.ByteContentItem{Type:dlppb.ByteContentItem_IMAGE_JPEG,Data:data,},},},}// Send the request.resp,err:=client.InspectContent(ctx,req)iferr!=nil{returnfmt.Errorf("InspectContent: %w",err)}// Process the results.fmt.Fprintf(w,"Findings: %d\n",len(resp.Result.Findings))for_,f:=rangeresp.Result.Findings{fmt.Fprintf(w,"\tQuote: %s\n",f.Quote)fmt.Fprintf(w,"\tInfo type: %s\n",f.InfoType.Name)fmt.Fprintf(w,"\tLikelihood: %s\n",f.Likelihood)}returnnil}
importcom.google.cloud.dlp.v2.DlpServiceClient;importcom.google.privacy.dlp.v2.ByteContentItem;importcom.google.privacy.dlp.v2.ByteContentItem.BytesType;importcom.google.privacy.dlp.v2.ContentItem;importcom.google.privacy.dlp.v2.Finding;importcom.google.privacy.dlp.v2.InspectContentRequest;importcom.google.privacy.dlp.v2.InspectContentResponse;importcom.google.privacy.dlp.v2.LocationName;importcom.google.protobuf.ByteString;importjava.io.FileInputStream;importjava.io.IOException;classInspectImageFileAllInfoTypes{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="my-project-id";StringinputPath="src/test/resources/sensitive-data-image.jpeg";inspectImageFileAllInfoTypes(projectId,inputPath);}staticvoidinspectImageFileAllInfoTypes(StringprojectId,StringinputPath)throwsIOException{// 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(DlpServiceClientdlp=DlpServiceClient.create()){// Specify the content to be inspected.ByteStringfileBytes=ByteString.readFrom(newFileInputStream(inputPath));ByteContentItembyteItem=ByteContentItem.newBuilder().setType(BytesType.IMAGE_JPEG).setData(fileBytes).build();// Construct the Inspect request to be sent by the client.// Do not specify the type of info to inspect.InspectContentRequestrequest=InspectContentRequest.newBuilder().setParent(LocationName.of(projectId,"global").toString()).setItem(ContentItem.newBuilder().setByteItem(byteItem).build()).build();// Use the client to send the API request.InspectContentResponseresponse=dlp.inspectContent(request);// Parse the response and process results.System.out.println("Findings: "+response.getResult().getFindingsCount());for(Findingf:response.getResult().getFindingsList()){System.out.println("\tQuote: "+f.getQuote());System.out.println("\tInfo type: "+f.getInfoType().getName());System.out.println("\tLikelihood: "+f.getLikelihood());}}}}
// Imports the Google Cloud Data Loss Prevention libraryconstDLP=require('@google-cloud/dlp');constmime=require('mime');constfs=require('fs');// Instantiates a clientconstdlp=newDLP.DlpServiceClient();// The project ID to run the API call under// const projectId = 'my-project';// Image Path// const imagePath = './test.jpeg';asyncfunctioninspectImageFileAllType(){letfileBytes=null;letfileTypeConstant=null;try{// Load ImagefileTypeConstant=['image/jpeg','image/bmp','image/png','image/svg'].indexOf(mime.getType(imagePath))+1;fileBytes=Buffer.from(fs.readFileSync(imagePath)).toString('base64');}catch(error){console.error(error.message);return;}// Specify the content to be inspected.constitem={byteItem:{type:fileTypeConstant,data:fileBytes,},};// Construct the Inspect request to be sent by the client.// Do not specify the type of info to inspect.constrequest={parent:`projects/${projectId}/locations/global`,item:item,inspectConfig:{includeQuote:true,},};// Use the client to send the API request.const[response]=awaitdlp.inspectContent(request);// Print findings.constfindings=response.result.findings;if(findings.length > 0){console.log(`Findings: ${findings.length}\n`);findings.forEach(finding=>{console.log(`InfoType: ${finding.infoType.name}`);console.log(`\tQuote: ${finding.quote}`);console.log(`\tLikelihood: ${finding.likelihood} \n`);});}else{console.log('No findings.');}}inspectImageFileAllType();
use Google\Cloud\Dlp\V2\ByteContentItem;use Google\Cloud\Dlp\V2\ByteContentItem\BytesType;use Google\Cloud\Dlp\V2\Client\DlpServiceClient;use Google\Cloud\Dlp\V2\ContentItem;use Google\Cloud\Dlp\V2\InspectContentRequest;use Google\Cloud\Dlp\V2\Likelihood;/** * Inspect image for sensitive data with infoTypes. * To inspect an image for sensitive data, you submit a base64-encoded image to the Cloud DLP API's * content.inspect method. Unless you specify information types (infoTypes) to search for, Cloud DLP * searches for the most common infoTypes. * * @param string $projectId The Google Cloud project id to use as a parent resource. * @param string $inputPath The image path to inspect. */function inspect_image_all_infotypes( // TODO(developer): Replace sample parameters before running the code. string $projectId, string $inputPath = './test/data/test.png'): void { // Instantiate a client. $dlp = new DlpServiceClient(); // Get the bytes of the file. $fileBytes = (new ByteContentItem()) ->setType(BytesType::IMAGE_PNG) ->setData(file_get_contents($inputPath)); $parent = "projects/$projectId/locations/global"; // Specify what content you want the service to Inspect. $item = (new ContentItem()) ->setByteItem($fileBytes); // Run request. $inspectContentRequest = (new InspectContentRequest()) ->setParent($parent) ->setItem($item); $response = $dlp->inspectContent($inspectContentRequest); // Print the results. $findings = $response->getResult()->getFindings(); if (count($findings) == 0) { printf('No findings.' . PHP_EOL); } else { printf('Findings:' . PHP_EOL); foreach ($findings as $finding) { printf(' Info type: %s' . PHP_EOL, $finding->getInfoType()->getName()); printf(' Likelihood: %s' . PHP_EOL, Likelihood::name($finding->getLikelihood())); } }}
importgoogle.cloud.dlpdefinspect_image_file_all_infotypes(project:str,filename:str,include_quote:bool=True,)-> None:"""Uses the Data Loss Prevention API to analyze strings for protected data in image file. Args: project: The Google Cloud project id to use as a parent resource. filename: The path to the file to inspect. include_quote: Boolean for whether to display a quote of the detected information in the results. 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 image file's byte data.withopen(filename,mode="rb")asf: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.inspect_content(request={"parent":parent,"inspect_config":{"include_quote":include_quote},"item":{"byte_item":byte_item},})# Print out the results.print("Findings: ",response.result.findings.count)ifresponse.result.findings:forfindinginresponse.result.findings:print(f"Quote: {finding.quote}")print(f"Info type: {finding.info_type.name}")print(f"Likelihood: {finding.likelihood}")else:print("No findings.")
REST
To inspect this image for default infoTypes, send the following JSON to
the content.inspect method:
usingSystem;usingSystem.IO;usingSystem.Linq;usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.Dlp.V2;usingGoogle.Protobuf;publicclassInspectImageForSensitiveDataWithListedInfoTypes{publicstaticInspectContentResponseInspectImage(stringprojectId,stringfilePath){// Instantiate dlp client.vardlp=DlpServiceClient.Create();// Construct the content item by providing the image file and its type.varcontentItem=newContentItem{ByteItem=newByteContentItem{Type=ByteContentItem.Types.BytesType.ImagePng,Data=ByteString.FromStream(newFileStream(filePath,FileMode.Open))}};// Specify the type of info the inspection will look for.varinfoTypes=newInfoType[]{newInfoType{Name="PHONE_NUMBER"},newInfoType{Name="EMAIL_ADDRESS"},newInfoType{Name="US_SOCIAL_SECURITY_NUMBER"}};// Construct the Inspect config.varinspectConfig=newInspectConfig{InfoTypes={infoTypes},IncludeQuote=true};// Construct the request.varrequest=newInspectContentRequest{ParentAsLocationName=newLocationName(projectId,"global"),InspectConfig=inspectConfig,Item=contentItem};// Call the API.InspectContentResponseresponse=dlp.InspectContent(request);// Inspect the response.varresultFindings=response.Result.Findings;Console.WriteLine($"Findings: {resultFindings.Count}");foreach(varfinresultFindings){vardata=fromlocationinf.Location.ContentLocationsfrombinlocation.ImageLocation.BoundingBoxesselectnew{b.Height,b.Width,b.Top,b.Left};Console.WriteLine("Info type: "+f.InfoType.Name);Console.WriteLine("\tQuote: "+f.Quote);Console.WriteLine("\tImageLocations: "+string.Join(",",data));Console.WriteLine("\tLikelihood: "+f.Likelihood);}returnresponse;}}
import("context""fmt""io""os"dlp"cloud.google.com/go/dlp/apiv2""cloud.google.com/go/dlp/apiv2/dlppb")// inspectImageFileListedInfoTypes inspects an image for sensitive data listed infoTypes.funcinspectImageFileListedInfoTypes(wio.Writer,projectID,filePathstring)error{// projectId := "my-project-id"// filePath := "testdata/image.jpg"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)iferr!=nil{returnerr}// Closing the client safely cleans up background resources.deferclient.Close()// Read a image filedata,err:=os.ReadFile(filePath)iferr!=nil{returnerr}// Specify the type and content to be inspected.item:=&dlppb.ContentItem{DataItem:&dlppb.ContentItem_ByteItem{ByteItem:&dlppb.ByteContentItem{Type:dlppb.ByteContentItem_IMAGE_JPEG,Data:data,},},}// Construct the configuration for the Inspect request.inspectConfig:=&dlppb.InspectConfig{InfoTypes:[]*dlppb.InfoType{{Name:"PHONE_NUMBER"},{Name:"EMAIL_ADDRESS"},{Name:"US_SOCIAL_SECURITY_NUMBER"},},IncludeQuote:true,}// Construct the Inspect request to be sent by the client.req:=&dlppb.InspectContentRequest{Parent:fmt.Sprintf("projects/%s/locations/global",projectID),Item:item,InspectConfig:inspectConfig,}// Send the request.resp,err:=client.InspectContent(ctx,req)iferr!=nil{returnerr}// Process the results.fmt.Fprintf(w,"Findings: %d\n",len(resp.Result.Findings))for_,f:=rangeresp.Result.Findings{fmt.Fprintf(w,"\tQuote: %s\n",f.Quote)fmt.Fprintf(w,"\tInfo type: %s\n",f.InfoType.Name)fmt.Fprintf(w,"\tLikelihood: %s\n",f.Likelihood)}returnnil}
importcom.google.cloud.dlp.v2.DlpServiceClient;importcom.google.privacy.dlp.v2.ByteContentItem;importcom.google.privacy.dlp.v2.ByteContentItem.BytesType;importcom.google.privacy.dlp.v2.ContentItem;importcom.google.privacy.dlp.v2.Finding;importcom.google.privacy.dlp.v2.InfoType;importcom.google.privacy.dlp.v2.InspectConfig;importcom.google.privacy.dlp.v2.InspectContentRequest;importcom.google.privacy.dlp.v2.InspectContentResponse;importcom.google.privacy.dlp.v2.LocationName;importcom.google.protobuf.ByteString;importjava.io.FileInputStream;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;classInspectImageFileListedInfoTypes{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="my-project-id";StringinputPath="src/test/resources/sensitive-data-image.jpeg";inspectImageFileListedInfoTypes(projectId,inputPath);}staticvoidinspectImageFileListedInfoTypes(StringprojectId,StringinputPath)throwsIOException{// 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(DlpServiceClientdlp=DlpServiceClient.create()){// Specify the content to be inspected.ByteStringfileBytes=ByteString.readFrom(newFileInputStream(inputPath));ByteContentItembyteItem=ByteContentItem.newBuilder().setType(BytesType.IMAGE_JPEG).setData(fileBytes).build();// Specify the type of info the inspection will look for.List<InfoType>infoTypes=newArrayList<>();// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info typesfor(StringtypeName:newString[]{"US_SOCIAL_SECURITY_NUMBER","EMAIL_ADDRESS","PHONE_NUMBER"}){infoTypes.add(InfoType.newBuilder().setName(typeName).build());}// Construct the configuration for the Inspect request.InspectConfiginspectConfig=InspectConfig.newBuilder().addAllInfoTypes(infoTypes).build();// Construct the Inspect request to be sent by the client.InspectContentRequestrequest=InspectContentRequest.newBuilder().setParent(LocationName.of(projectId,"global").toString()).setItem(ContentItem.newBuilder().setByteItem(byteItem).build()).setInspectConfig(inspectConfig).build();// Use the client to send the API request.InspectContentResponseresponse=dlp.inspectContent(request);// Parse the response and process results.System.out.println("Findings: "+response.getResult().getFindingsCount());for(Findingf:response.getResult().getFindingsList()){System.out.println("\tQuote: "+f.getQuote());System.out.println("\tInfo type: "+f.getInfoType().getName());System.out.println("\tLikelihood: "+f.getLikelihood());}}}}
// Imports the Google Cloud Data Loss Prevention libraryconstDLP=require('@google-cloud/dlp');constmime=require('mime');constfs=require('fs');// Instantiates a clientconstdlp=newDLP.DlpServiceClient();// The project ID to run the API call under// const imagePath = './test.pdf';// InfoTypesconstinfoTypes=[{name:'PHONE_NUMBER'},{name:'EMAIL_ADDRESS'},{name:'US_SOCIAL_SECURITY_NUMBER'},];asyncfunctioninspectImageFileListedInfoTypes(){letfileBytes=null;letfileTypeConstant=null;try{// Load ImagefileTypeConstant=['image/jpeg','image/bmp','image/png','image/svg'].indexOf(mime.getType(imagePath))+1;fileBytes=Buffer.from(fs.readFileSync(imagePath)).toString('base64');}catch(error){console.log(error);return;}// Specify item to inspectconstitem={byteItem:{type:fileTypeConstant,data:fileBytes,},};// Specify inspect configuration to match information with mentioned infotypes.constinspectConfig={infoTypes:infoTypes,includeQuote:true,};// Combine configurations into a request for the service.constrequest={parent:`projects/${projectId}/locations/global`,inspectConfig:inspectConfig,item:item,};// Use the client to send the request.const[response]=awaitdlp.inspectContent(request);// Print Findingsconstfindings=response.result.findings;if(findings.length > 0){console.log(`Findings: ${findings.length}\n`);findings.forEach(finding=>{console.log(`InfoType: ${finding.infoType.name}`);console.log(`\tQuote: ${finding.quote}`);console.log(`\tLikelihood: ${finding.likelihood} \n`);});}else{console.log('No findings.');}}inspectImageFileListedInfoTypes();
use Google\Cloud\Dlp\V2\ByteContentItem;use Google\Cloud\Dlp\V2\ByteContentItem\BytesType;use Google\Cloud\Dlp\V2\Client\DlpServiceClient;use Google\Cloud\Dlp\V2\ContentItem;use Google\Cloud\Dlp\V2\InfoType;use Google\Cloud\Dlp\V2\InspectConfig;use Google\Cloud\Dlp\V2\InspectContentRequest;use Google\Cloud\Dlp\V2\Likelihood;/** * Inspect an image for sensitive data with listed infoTypes. * If you want to inspect an image for only certain sensitive data types, specify their corresponding * built-in infoTypes. * * @param string $projectId The Google Cloud project id to use as a parent resource. * @param string $inputPath The image path to inspect. */function inspect_image_listed_infotypes( // TODO(developer): Replace sample parameters before running the code. string $projectId, string $inputPath = './test/data/test.png'): void { // Instantiate a client. $dlp = new DlpServiceClient(); // Get the bytes of the file. $fileBytes = (new ByteContentItem()) ->setType(BytesType::IMAGE_PNG) ->setData(file_get_contents($inputPath)); $parent = "projects/$projectId/locations/global"; // Specify what content you want the service to Inspect. $item = (new ContentItem()) ->setByteItem($fileBytes); // Create inspect config configuration. $inspectConfig = (new InspectConfig()) // The infoTypes of information to match. ->setInfoTypes([ (new InfoType())->setName('PHONE_NUMBER'), (new InfoType())->setName('EMAIL_ADDRESS'), (new InfoType())->setName('US_SOCIAL_SECURITY_NUMBER') ]); // Run request. $inspectContentRequest = (new InspectContentRequest()) ->setParent($parent) ->setInspectConfig($inspectConfig) ->setItem($item); $response = $dlp->inspectContent($inspectContentRequest); // Print the results. $findings = $response->getResult()->getFindings(); if (count($findings) == 0) { printf('No findings.' . PHP_EOL); } else { printf('Findings:' . PHP_EOL); foreach ($findings as $finding) { printf(' Info type: %s' . PHP_EOL, $finding->getInfoType()->getName()); printf(' Likelihood: %s' . PHP_EOL, Likelihood::name($finding->getLikelihood())); } }}
fromtypingimportListimportgoogle.cloud.dlpdefinspect_image_file_listed_infotypes(project:str,filename:str,info_types:List[str],include_quote:bool=True,)-> None:"""Uses the Data Loss Prevention API to analyze strings in an image for data matching the given infoTypes. Args: project: The Google Cloud project id to use as a parent resource. filename: The path of the image file to inspect. info_types: A list of strings representing infoTypes to look for. A full list of info type categories can be fetched from the API. include_quote: Boolean for whether to display a matching snippet of the detected information in the results. """# Instantiate a client.dlp=google.cloud.dlp_v2.DlpServiceClient()# Prepare info_types by converting the list of strings into a list of# dictionaries.info_types=[{"name":info_type}forinfo_typeininfo_types]# Construct the configuration dictionary.inspect_config={"info_types":info_types,"include_quote":include_quote,}# Construct the byte_item, containing the image file's byte data.withopen(filename,mode="rb")asf: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.inspect_content(request={"parent":parent,"inspect_config":inspect_config,"item":{"byte_item":byte_item},})# Print out the results.ifresponse.result.findings:forfindinginresponse.result.findings:print(f"Info type: {finding.info_type.name}")ifinclude_quote:print(f"Quote: {finding.quote}")print(f"Likelihood: {finding.likelihood}\n")else:print("No findings.")
REST
Consider the original image from the previous section. To inspect for only email
addresses and telephone numbers, send the following JSON to the
content.inspect method.
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingGoogle.Api.Gax.ResourceNames;usingGoogle.Cloud.Dlp.V2;usingGoogle.Protobuf;publicclassInspectImage{publicstaticInspectContentResponseInspect(stringprojectId,stringfilePath,IEnumerable<InfoType>infoTypes=null){// Instantiate dlp client.vardlp=DlpServiceClient.Create();// Construct the content item by setting the type of image and data to be inspected.varcontentItem=newContentItem{ByteItem=newByteContentItem{Type=ByteContentItem.Types.BytesType.ImagePng,Data=ByteString.FromStream(newFileStream(filePath,FileMode.Open))}};// Construct the Inspect config by specifying the type of info to be inspected.varinspectConfig=newInspectConfig{InfoTypes={infoTypes??newInfoType[]{newInfoType{Name="PHONE_NUMBER"},newInfoType{Name="EMAIL_ADDRESS"},newInfoType{Name="CREDIT_CARD_NUMBER"}}},IncludeQuote=true};// Construct the request.varrequest=newInspectContentRequest{ParentAsLocationName=newLocationName(projectId,"global"),InspectConfig=inspectConfig,Item=contentItem};// Call the API.InspectContentResponseresponse=dlp.InspectContent(request);// Inspect the response.varresultFindings=response.Result.Findings;Console.WriteLine($"Findings: {resultFindings.Count}\n");// Print the results.foreach(varfinresultFindings){vardata=fromlocationinf.Location.ContentLocationsfrombinlocation.ImageLocation.BoundingBoxesselectnew{b.Height,b.Width,b.Top,b.Left};Console.WriteLine("Info type: "+f.InfoType.Name);Console.WriteLine("\tQuote: "+f.Quote);Console.WriteLine("\tImageLocations: "+string.Join(",",data));Console.WriteLine("\tLikelihood: "+f.Likelihood);}returnresponse;}}
import("context""fmt""io""os"dlp"cloud.google.com/go/dlp/apiv2""cloud.google.com/go/dlp/apiv2/dlppb")// inspectImageFile inspects an image file for sensitive datafuncinspectImageFile(wio.Writer,projectID,filePathstring)error{// projectId := "my-project-id"// filePath := "inspect/testdata/test.png"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)iferr!=nil{returnerr}// Closing the client safely cleans up background resources.deferclient.Close()// Read a image filedata,err:=os.ReadFile(filePath)iferr!=nil{returnerr}// Specify the type and content to be inspected.item:=&dlppb.ContentItem{DataItem:&dlppb.ContentItem_ByteItem{ByteItem:&dlppb.ByteContentItem{Type:dlppb.ByteContentItem_IMAGE,Data:data,},},}// Construct the configuration for the Inspect request.inspectConfig:=&dlppb.InspectConfig{InfoTypes:[]*dlppb.InfoType{{Name:"PHONE_NUMBER"},{Name:"EMAIL_ADDRESS"},{Name:"CREDIT_CARD_NUMBER"},},IncludeQuote:true,}// Construct the Inspect request to be sent by the client.req:=&dlppb.InspectContentRequest{Parent:fmt.Sprintf("projects/%s/locations/global",projectID),Item:item,InspectConfig:inspectConfig,}// Send the request.resp,err:=client.InspectContent(ctx,req)iferr!=nil{returnerr}// Process the results.fmt.Fprintf(w,"Findings: %d\n",len(resp.Result.Findings))for_,f:=rangeresp.Result.Findings{fmt.Fprintf(w,"\tQuote: %s\n",f.Quote)fmt.Fprintf(w,"\tInfo type: %s\n",f.InfoType.Name)fmt.Fprintf(w,"\tLikelihood: %s\n",f.Likelihood)}returnnil}
importcom.google.cloud.dlp.v2.DlpServiceClient;importcom.google.privacy.dlp.v2.ByteContentItem;importcom.google.privacy.dlp.v2.ByteContentItem.BytesType;importcom.google.privacy.dlp.v2.ContentItem;importcom.google.privacy.dlp.v2.Finding;importcom.google.privacy.dlp.v2.InfoType;importcom.google.privacy.dlp.v2.InspectConfig;importcom.google.privacy.dlp.v2.InspectContentRequest;importcom.google.privacy.dlp.v2.InspectContentResponse;importcom.google.privacy.dlp.v2.LocationName;importcom.google.protobuf.ByteString;importjava.io.FileInputStream;importjava.io.IOException;importjava.util.ArrayList;importjava.util.List;publicclassInspectImageFile{publicstaticvoidmain(String[]args)throwsException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringfilePath="path/to/image.png";inspectImageFile(projectId,filePath);}// Inspects the specified image file.publicstaticvoidinspectImageFile(StringprojectId,StringfilePath)throwsIOException{// 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(DlpServiceClientdlp=DlpServiceClient.create()){// Specify the type and content to be inspected.ByteStringfileBytes=ByteString.readFrom(newFileInputStream(filePath));ByteContentItembyteItem=ByteContentItem.newBuilder().setType(BytesType.IMAGE).setData(fileBytes).build();ContentItemitem=ContentItem.newBuilder().setByteItem(byteItem).build();// Specify the type of info the inspection will look for.List<InfoType>infoTypes=newArrayList<>();// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info typesfor(StringtypeName:newString[]{"PHONE_NUMBER","EMAIL_ADDRESS","CREDIT_CARD_NUMBER"}){infoTypes.add(InfoType.newBuilder().setName(typeName).build());}// Construct the configuration for the Inspect request.InspectConfigconfig=InspectConfig.newBuilder().addAllInfoTypes(infoTypes).setIncludeQuote(true).build();// Construct the Inspect request to be sent by the client.InspectContentRequestrequest=InspectContentRequest.newBuilder().setParent(LocationName.of(projectId,"global").toString()).setItem(item).setInspectConfig(config).build();// Use the client to send the API request.InspectContentResponseresponse=dlp.inspectContent(request);// Parse the response and process results.System.out.println("Findings: "+response.getResult().getFindingsCount());for(Findingf:response.getResult().getFindingsList()){System.out.println("\tQuote: "+f.getQuote());System.out.println("\tInfo type: "+f.getInfoType().getName());System.out.println("\tLikelihood: "+f.getLikelihood());}}}}
// Imports the Google Cloud Data Loss Prevention libraryconstDLP=require('@google-cloud/dlp');constmime=require('mime');constfs=require('fs');// Instantiates a clientconstdlp=newDLP.DlpServiceClient();// The project ID to run the API call under// const imagePath = './test.jpeg';// InfoTypesconstinfoTypes=[{name:'PHONE_NUMBER'},{name:'EMAIL_ADDRESS'},{name:'CREDIT_CARD_NUMBER'},];asyncfunctioninspectImageFile(){letfileBytes=null;letfileTypeConstant=null;try{// Load ImagefileTypeConstant=['image/jpeg','image/bmp','image/png','image/svg'].indexOf(mime.getType(imagePath))+1;fileBytes=Buffer.from(fs.readFileSync(imagePath)).toString('base64');}catch(error){console.log(error);return;}// Specify item to inspectconstitem={byteItem:{type:fileTypeConstant,data:fileBytes,},};// Specify inspect configuration to match information with mentioned infotypes.constinspectConfig={infoTypes:infoTypes,includeQuote:true,};// Combine configurations into a request for the service.constrequest={parent:`projects/${projectId}/locations/global`,inspectConfig:inspectConfig,item:item,};// Use the client to send the request.const[response]=awaitdlp.inspectContent(request);// Print Findingsconstfindings=response.result.findings;if(findings.length > 0){console.log(`Findings: ${findings.length}\n`);findings.forEach(finding=>{console.log(`InfoType: ${finding.infoType.name}`);console.log(`\tQuote: ${finding.quote}`);console.log(`\tLikelihood: ${finding.likelihood} \n`);});}else{console.log('No findings.');}}inspectImageFile();
importgoogle.cloud.dlpdefinspect_image_file(project:str,filename:str,include_quote:bool=True,)-> None:"""Uses the Data Loss Prevention API to analyze strings for protected data in image file. Args: project: The Google Cloud project id to use as a parent resource. filename: The path to the file to inspect. include_quote: Boolean for whether to display a quote of the detected information in the results. """# Instantiate a client.dlp=google.cloud.dlp_v2.DlpServiceClient()# Prepare info_types by converting the list of strings into a list of# dictionaries.info_types=["PHONE_NUMBER","EMAIL_ADDRESS","CREDIT_CARD_NUMBER"]info_types=[{"name":info_type}forinfo_typeininfo_types]# Construct the configuration for the Inspect request.inspect_config={"info_types":info_types,"include_quote":include_quote,}# Construct the byte_item, containing the image file's byte data.withopen(filename,mode="rb")asf:byte_item={"type_":"IMAGE","data":f.read()}# Convert the project id into a full resource id.parent=f"projects/{project}/locations/global"# Call the API.response=dlp.inspect_content(request={"parent":parent,"inspect_config":inspect_config,"item":{"byte_item":byte_item},})# Parse the response and process results.ifresponse.result.findings:forfindinginresponse.result.findings:print(f"Quote: {finding.quote}")print(f"Info type: {finding.info_type.name}")print(f"Likelihood: {finding.likelihood}")else:print("No findings.")
Try it out
You can try each of these examples out yourself—or experiment with your
own images—in the API Explorer on the reference page for
content.inspect:
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2026-07-22 UTC."],[],[]]