|
| 1 | +--- |
| 2 | +title: "Quickstart: Analyze image content with TypeScript" |
| 3 | +description: In this quickstart, get started using the Azure AI Content Safety TypeScript SDK to analyze image content for objectionable material. |
| 4 | +author: PatrickFarley |
| 5 | +manager: nitinme |
| 6 | +ms.service: azure-ai-content-safety |
| 7 | +ms.custom: |
| 8 | +ms.topic: include |
| 9 | +ms.date: 07/11/2025 |
| 10 | +ms.author: pafarley |
| 11 | +--- |
| 12 | + |
| 13 | +[Reference documentation](https://www.npmjs.com/package/@azure-rest/ai-content-safety/v/1.0.0) | [Library source code](https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/contentsafety/ai-content-safety-rest) | [Package (npm)](https://www.npmjs.com/package/@azure-rest/ai-content-safety) | [Samples](https://github.com/Azure-Samples/AzureAIContentSafety/tree/main/js/1.0.0) | |
| 14 | + |
| 15 | + |
| 16 | +## Prerequisites |
| 17 | + |
| 18 | +* An Azure subscription - [Create one for free](https://azure.microsoft.com/free/cognitive-services/) |
| 19 | +* [Node.js LTS](https://nodejs.org/) |
| 20 | +* [TypeScript](https://www.typescriptlang.org/) |
| 21 | +* [Visual Studio Code](https://code.visualstudio.com/) |
| 22 | +* Once you have your Azure subscription, <a href="https://aka.ms/acs-create" title="Create a Content Safety resource" target="_blank">create a Content Safety resource </a> in the Azure portal to get your key and endpoint. Enter a unique name for your resource, select your subscription, and select a resource group, supported region (see [Region availability](/azure/ai-services/content-safety/overview#region-availability)), and supported pricing tier. Then select **Create**. |
| 23 | + * The resource takes a few minutes to deploy. After it finishes, Select **go to resource**. In the left pane, under **Resource Management**, select **Subscription Key and Endpoint**. The endpoint and either of the keys are used to call APIs. |
| 24 | + |
| 25 | +## Set up local development environment |
| 26 | + |
| 27 | +1. Create a new directory for your project and navigate to it: |
| 28 | + |
| 29 | + ```console |
| 30 | + mkdir content-safety-image-analysis |
| 31 | + cd content-safety-image-analysis |
| 32 | + code . |
| 33 | + ``` |
| 34 | + |
| 35 | +2. Create a new package for ESM modules in your project directory: |
| 36 | + |
| 37 | + ```console |
| 38 | + npm init -y |
| 39 | + npm pkg set type=module |
| 40 | + ``` |
| 41 | + |
| 42 | +3. Install the required packages: |
| 43 | + |
| 44 | + ```console |
| 45 | + npm install @azure-rest/ai-content-safety |
| 46 | + ``` |
| 47 | + |
| 48 | +4. Install development dependencies: |
| 49 | + |
| 50 | + ```console |
| 51 | + npm install typescript @types/node --save-dev |
| 52 | + ``` |
| 53 | + |
| 54 | +5. Create a `tsconfig.json` file in your project directory: |
| 55 | + |
| 56 | + ```json |
| 57 | + { |
| 58 | + "compilerOptions": { |
| 59 | + "target": "es2022", |
| 60 | + "module": "esnext", |
| 61 | + "moduleResolution": "bundler", |
| 62 | + "rootDir": "./src", |
| 63 | + "outDir": "./dist/", |
| 64 | + "esModuleInterop": true, |
| 65 | + "forceConsistentCasingInFileNames": true, |
| 66 | + "strict": true, |
| 67 | + "skipLibCheck": true, |
| 68 | + "declaration": true, |
| 69 | + "sourceMap": true, |
| 70 | + "resolveJsonModule": true, |
| 71 | + "moduleDetection": "force", |
| 72 | + "allowSyntheticDefaultImports": true, |
| 73 | + "verbatimModuleSyntax": false |
| 74 | + }, |
| 75 | + "include": [ |
| 76 | + "src/**/*.ts" |
| 77 | + ], |
| 78 | + "exclude": [ |
| 79 | + "node_modules/**/*", |
| 80 | + "**/*.spec.ts" |
| 81 | + ] |
| 82 | + } |
| 83 | + ``` |
| 84 | + |
| 85 | +6. Update `package.json` to include a script for building TypeScript files: |
| 86 | + |
| 87 | + ```json |
| 88 | + "scripts": { |
| 89 | + "build": "tsc", |
| 90 | + "start": "node dist/index.js" |
| 91 | + } |
| 92 | + ``` |
| 93 | + |
| 94 | +7. Create a `resources` folder and add a sample image to it. |
| 95 | + |
| 96 | +8. Create a `src` directory for your TypeScript code. |
| 97 | + |
| 98 | +[!INCLUDE [Create environment variables](../env-vars.md)] |
| 99 | + |
| 100 | +## Analyze image content |
| 101 | + |
| 102 | +Create a new file in your `src` directory, `index.ts` and paste in the following code. Replace the string used to create the `imagePath` variable with the path to your sample image. |
| 103 | + |
| 104 | +```typescript |
| 105 | +import ContentSafetyClient, { |
| 106 | + isUnexpected, |
| 107 | + AnalyzeImageParameters, |
| 108 | + AnalyzeImage200Response, |
| 109 | + AnalyzeImageDefaultResponse, |
| 110 | + AnalyzeImageOptions, |
| 111 | + ImageCategoriesAnalysisOutput |
| 112 | +} from "@azure-rest/ai-content-safety"; |
| 113 | +import { AzureKeyCredential } from "@azure/core-auth"; |
| 114 | +import * as fs from "fs"; |
| 115 | +import * as path from "path"; |
| 116 | +import { fileURLToPath } from "url"; |
| 117 | + |
| 118 | +// Create __dirname equivalent for ESM modules |
| 119 | +const __filename = fileURLToPath(import.meta.url); |
| 120 | +const __dirname = path.dirname(__filename); |
| 121 | + |
| 122 | +// Get endpoint and key from environment variables |
| 123 | +const endpoint = process.env.CONTENT_SAFETY_ENDPOINT; |
| 124 | +const key = process.env.CONTENT_SAFETY_KEY; |
| 125 | + |
| 126 | +if (!endpoint || !key) { |
| 127 | + throw new Error("Missing required environment variables CONTENT_SAFETY_ENDPOINT or CONTENT_SAFETY_KEY"); |
| 128 | +} |
| 129 | + |
| 130 | +try { |
| 131 | + |
| 132 | + const credential = new AzureKeyCredential(key); |
| 133 | + const client = ContentSafetyClient(endpoint, credential); |
| 134 | + |
| 135 | + const imagePath = path.join(__dirname, '../resources/image.jpg'); |
| 136 | + |
| 137 | + const imageBuffer = fs.readFileSync(imagePath); |
| 138 | + const base64Image = imageBuffer.toString("base64"); |
| 139 | + const analyzeImageOption: AnalyzeImageOptions = { image: { content: base64Image } }; |
| 140 | + const analyzeImageParameters: AnalyzeImageParameters = { body: analyzeImageOption }; |
| 141 | + |
| 142 | + const result: AnalyzeImage200Response | AnalyzeImageDefaultResponse = await client.path("/image:analyze").post(analyzeImageParameters); |
| 143 | + |
| 144 | + if (isUnexpected(result)) { |
| 145 | + throw result; |
| 146 | + } |
| 147 | + |
| 148 | + const categoriesAnalysis = result.body.categoriesAnalysis as ImageCategoriesAnalysisOutput[]; |
| 149 | + |
| 150 | + for (const analysis of categoriesAnalysis) { |
| 151 | + console.log(`${analysis.category} severity: ${analysis.severity}`); |
| 152 | + } |
| 153 | +} catch (error) { |
| 154 | + console.error("Error analyzing image:", error); |
| 155 | +} |
| 156 | +``` |
| 157 | + |
| 158 | +## Build and run the sample |
| 159 | + |
| 160 | +1. Compile the TypeScript code: |
| 161 | + |
| 162 | + ```console |
| 163 | + npm run build |
| 164 | + ``` |
| 165 | + |
| 166 | +1. Run the compiled JavaScript: |
| 167 | + |
| 168 | + ```console |
| 169 | + node dist/index.js |
| 170 | + ``` |
| 171 | + |
| 172 | +## Output |
| 173 | + |
| 174 | +```console |
| 175 | +Hate severity: 0 |
| 176 | +SelfHarm severity: 0 |
| 177 | +Sexual severity: 0 |
| 178 | +Violence severity: 0 |
| 179 | +``` |
0 commit comments