CLOVA OCR General API

Version

문서 버전 변경일자 변경사항
v1.0.0 2019-12-05 최초 작성
v1.0.1 2020-02-21 General OCR 응답 바디에 boundingPoly 정보 제공
v2.0.0 2020-03-26 CLOVA OCR 프리미엄 모델 제공으로 멀티박스, 체크박스 인식 기능 추가
요청 버전에 따라 (V1/V2) 결과값에 bounding 및 boundingPoly 정보 제공
※ V2 사용 시 boundingPoly 표시 (권장)
v2.0.1 2021-01-21 General OCR JSON 줄바꿈 정보 제공
ImageField 객체 내 subFiled 삭제
v2.0.1 2021-02-04 convertedImageInfo 필드 추가
v2.0.2 2024-09-26 콘텐츠 항목 정리 및 문구 개선

개요

본 문서에서는 General OCR의 요청 및 응답 바디에 대해 설명하고 API 구현 예제를 제공합니다.

참고

Post URL과 헤더, 에러코드에 대한 정보는 CLOVA OCR 개요 문서를 주십시오.

General OCR

요청 예시

{
  "version": "V2",
  "requestId": "string",
  "timestamp": 0,
  "lang":"ko",
  "images": [
    {
      "format": "jpg",
      "name": "test 1",
      "url": "https://www.ncloud.com/ocr-test/test.jpg"
    }
  ],
  "enableTableDetection": "false"
}

요청 바디

Content-Type : application/json

  • JSON 요청 바디 필드
필드명 필수 여부 타입 설명 제약 사항
version Y string V2: V2 엔진 호출 (권장)
V1: V1 엔진 호출
requestId Y string 임의의 UUID 값 입력
timestamp Y integer 임의의 timestamp 값을 숫자로 입력
lang N string OCR 인식을 요청할 언어 정보
ko: 한국어
ja: 일본어
zh-TW: 중국어(번체)
설정되지 않은 경우, 도메인의 언어 설정이 기본값으로 지정됨
콤마를 사용하여 다국어 호. (예 : "ko,ja,zh-TW")
images Y array JSON array로 작성하며 호출당 1개의 이미지 array만 작성 가능 General OCR은 50MB, Template OCR은 20MB (pdf, tiff는 50MB)까지 지원
images.format Y string jpg, jpeg, png, pdf, tiff 중 택일하여 이미지 포맷을 입력 General OCR은 pdf에 대해 최대 10페이지, Template OCR은 pdf, tiff에 대해 최대 5페이지까지 인식 가능
※ pdf/tiff는 1페이지당 1회 호출 요금이 부과됨
images.url N string 이미지 URL 입력 images.url 혹은 images.data 중 하나를 반드시 설정해야 함
이미지를 불러올 수 있는 공개된 URL이어야함
images.data N string BASE64 인코딩 된 이미지 데이터 입력 images.url 혹은 images.data 중 하나를 반드시 설정해야 하며
images.url과 images.data를 모두 설정할 경우 images.data가 우선
images.name Y string 임의의 이미지명 입력 이미지를 식별하는 데 사용되며 응답 결과 검증에 사용 능
enableTableDetection N Boolean true: 문서 이미지 내 표 영역을 자동으로 인식하여 텍스트와 함께 구조화된 형태로 제공
false: 표 인식 미수행 (기본값)
General OCR에서만 제공하는 기능
네이버 클라우드 플랫폼 콘솔에 생성한 도메인에서 표 추출 여부 토글을 ON으로 설정해야 사용 능가능

Content-Type : multipart/form-data

  • CURL example:
curl --request POST 'your apigw invoke url' \
--header 'X-OCR-SECRET: your secret key' \
--data-raw '{"images":[{"format":"jpg","name":"demo","url":"your image url"}],"requestId":"guide-json-demo","version":"V2","timestamp":1584062336793}'
  • Form-data 요청 바디 필드
필드명 필수 여부 타입 설명 제약 사항
version Y string V2: V2 엔진 호출 (권장)
V1: V1 엔진 호출
requestId Y string 임의의 UUID 값 입력
timestamp Y integer 임의의 timestamp 값을 숫자로 입력
lang N string OCR 인식을 요청할 언어 정보
ko: 한국어
ja: 일본어
zh-TW: 중국어(번체)
설정되지 않은 경우, 도메인의 언어 설정이 기본값으로 지정됨
콤마를 사용하여 다국어 호출 가능 (예 : "ko,ja,zh-TW")
images Y string JSON array로 작성하며, 호출당 1개의 이미지 array만 작성 가능 General OCR은 50MB, Template OCR은 20MB (pdf, tiff는 50MB)까지 지원
images.format Y string jpg, jpeg, png, pdf, tiff 중 택일하여 이미지 포맷을 입력 General OCR은 pdf에 대해 최대 10페이지, Template OCR은 pdf, tiff에 대해 최대 5페이지까지 인식 가능
※ pdf/tiff는 1페이지당 1회 호출 요금이 부과됨
images.name Y string 임의의 이미지명 입력 이미지를 식별하는 데 사용됨
응답 결과 검증에 사용 가능
enableTableDetection N Boolean true: 문서 이미지 내 표 영역을 자동으로 인식하여 텍스트와 함께 구조화된 형태로 제공
false: 표 인식 미수행 (기본값)
General OCR에서만 제공하는 기능
네이버 클라우드 플랫폼 콘솔에 생성한 도메인에서 표 추출 여부 토글을 ON으로 설정해야 사용

응답 예시

{
    "version": "V2",
    "requestId": "string",
    "timestamp": 1576569034247,
    "images": [{
        "uid": "9fd73a6aacad4025b3099a36ee55aacd",
        "name": "medium",
        "inferResult": "SUCCESS",
        "message": "SUCCESS",
        "validationResult": {
                "result": "NO_REQUESTED"
            },
            "convertedImageInfo": {
                "width": 1224,
                "height": 1584,
                "pageIndex": 0,
                "longImage": false
            },
        "fields": [{
                "valueType": "ALL",
                "inferText": "아름다운",
                "inferConfidence": 0.99992156,
                "type": "NORMAL",
                "lineBreak": true,
                "boundingPoly": {
                    "vertices": [{
                        "x": 2713.7295,
                        "y": 1277.0492
                    }, {
                        "x": 2713.7295,
                        "y": 977.7408
                    }, {
                        "x": 2841.4343,
                        "y": 977.7408
                    }, {
                        "x": 2841.4343,
                        "y": 1277.0492
                    }]
                }
            },
            {
                "valueType": "ALL",
                "inferText": "이",
                "inferConfidence": 0.99958915,
                "type": "NORMAL",
                "lineBreak": false,
                "boundingPoly": {
                    "vertices": [{
                        "x": 2314.6516,
                        "y": 1468.6066
                    }, {
                        "x": 2314.6516,
                        "y": 1328.9293
                    }, {
                        "x": 2426.3936,
                        "y": 1328.9293
                    }, {
                        "x": 2426.3936,
                        "y": 1468.6066
                    }]
                }
            },
            {
                "valueType": "ALL",
                "inferText": "세상",
                "inferConfidence": 0.9998707,
                "type": "NORMAL",
                "lineBreak": false,
                "boundingPoly": {
                    "vertices": [{
                        "x": 2314.6516,
                        "y": 1604.2931
                    }, {
                        "x": 2314.6516,
                        "y": 1460.625
                    }, {
                        "x": 2430.3843,
                        "y": 1460.625
                    }, {
                        "x": 2430.3843,
                        "y": 1604.2931
                    }]
                }
            }
        ]
    }]
}

응답 바디 (V2)

General OCR 요청 바디의 version을 V2로 설정했을 때의 응답 바디를 설명합니다.

1. 응답 바디 필드

필드명 유형 설명
uid string API의 유효성을 검사하기 위해 제공되는 고유 ID로, 유효성 검사 요청을 추적하는 데 사용
name string 요청 바디의 images.name에 입력한 이미지명
inferResult string 이미지 인식 결과
SUCCESS: 이미지 인식 성공
FAILURE: 이미지 인식 실패
ERROR: 이미지 인식 처리예외
message string 이미지 인식 결과에 대한 세부사항
성공 시 SUCCESS 표시
이미지 인식 실패 시 오류 메시지 표시
title string 이미지 타이틀
fields JSON array object ImageField 객체 참조
validationResult JSON object 유효성 검사 결과
validationResult.result string 유효성 검사 결과 코드
NO_REQUESTED: 검증 작업을 요청하지 않음
UNCHECKED: 동작 응답이 확인되지 않거나 응답이 미수락
ERROR: 검증 실행에 오류 발생
VALID: 검증 결과가 유효함
INVALID: 검증 결과가 유효하지 않음

UNCHECKED,ERROR,INVALID는 유효성 검사 실패로 표시됨
validationResult.message string Validation 세부 메시지로 항상 표시되는 값은 아님
convertedImageInfo JSON object 이미지 포맷이 pdf 또는 tiff인 경우 응답
좌표값은 이미지로 변환된 호출 파일을 기준으로 함.
convertedImageInfo.width integer 변환 이미지 가로 길이
convertedImageInfo.height integer 변환 이미지 세로 길이
convertedImageInfo.pageIndex integer pdf 또는 tiff의 페이지 인덱스
combineResult JSON object 판독 결과 결합
combineResult.name string 결합 필드 이름
combineResult.text string 각 필드별 출력값 및 고정 텍스트
tables JSON array object ImageTable Object 객체 참조

2. ImageField 객체 필드

필드명 유형 설명
name string 요청 바디의 images.name에 입력한 이미지명
valueType string 입력값 유형
ALL: 텍스트와 숫자
NUMERIC:숫자
inferText string 인식된 텍스트 값
type 필드의 값이 CHECKBOX인 경우 설정에서 지정한 응답값으로 대체됨
inferConfidence float 인식한 텍스트에 대한 신뢰도를 0~1 사이로 나타내며 값이 클수록 정확도가 높음
boundingPoly JSON array object boundingPoly 객체 참조
type string 인식된 이미지의 유형
NORMAL: 일반
MULTI_BOX: 멀티박스
CHECKBOX: 체크박스
checked boolean 체크박스 내 체크 여부를 표시
type 필드가 'CHECKBOX'인 경우만 지원
true: 체크되어 있음
false: 체크되어 있지 않음
lineBreak boolean 인식된 텍스트의 마지막 줄 여부를 표시
General OCR 호출 시에만 확인 가능
true: 마지막 텍스트
false: 마지막 텍스트 아님
subFields JSON Array >SubField 객체 참조.
Template OCR 호출 시에만 확인 가능

3. boundingPoly 객체 필드

필드명 유형 설명
vertices JSON array object vertices 객체 참조

4. vertices 객체 필드

필드명 유형 설명
x float x축 좌표값
y float y축 좌표값

5. ImageTable 객체 필드

필드명 유형 설명
boundingPoly JSON array object boundingPoly 객체 참조
inferText string 인식된 텍스트 값
cells JSON array object TableCell 객체 참조
inferConfidence float 인식한 텍스트에 대한 신뢰도를 0~1 사이로 나타내며 값이 클수록 정확도가 높음

6. TableCell 객체 필드

필드명 유형 설명
boundingPoly JSON array object boundingPoly 객체 참조
cellTextLines JSON array object 셀 내의 라인 정보를 표시
CellTextLine 객체 참조
inferConfidence float 인식한 텍스트에 대한 신뢰도를 0~1 사이로 나타내며 값이 클수록 정확도가 높음
rowSpan integer 도표 내 셀이 스팬해야 하는 가로열의 수
rowIndex integer 도표 내 전체 가로열 중 해당 가로열의 위치값
columnSpan integer 도표 내 셀이 스팬해야 하는 세로행의 수
columnIndex integer 도표 내 전체 세로행 중 해당 세로행의 위치값

7. CellTextLine 객체 필드

필드명 유형 설명
boundingPoly JSON array object boundingPoly 객체 참조
inferConfidence float 인식한 텍스트에 대한 신뢰도를 0~1 사이로 나타내며 값이 클수록 정확도가 높음
cellWords JSON array object 라인 내의 텍스트 정보를 표시
CellWord 객체 참조

8. CellWord 객체 필드

Field Name Data Type Description
boundingPoly JSON array object boundingPoly 객체 참조
inferConfidence float 인식한 텍스트에 대한 신뢰도를 0~1 사이로 나타내며 값이 클수록 정확도가 높음
inferText string 인식된 텍스트 값

응답 바디 (V1)

General OCR 요청 바디의 version을 V1로 설정했을 때의 응답 바디를 설명합니다.

1. 응답 바디 필드

필드명 유형 설명
uid string API의 유효성을 검사하기 위해 제공되는 고유 ID로, 유효성 검사 요청을 추적하는 데 사용
name string 요청 바디의 images.name에 입력한 이미지명
inferResult string 이미지 인식 결과
SUCCESS: 이미지 인식 성공
FAILURE: 이미지 인식 실패
ERROR: 이미지 인식 처리예외
message string 이미지 인식 결과에 대한 세부사항
성공 시 SUCCESS 표시
이미지 인식 실패 시 오류 메시지 표시
title string 이미지 타이틀
fields JSON array object ImageField 객체 참조
validationResult JSON object 유효성 검사 결과
validationResult.result string 유효성 검사 결과 코드
NO_REQUESTED: 검증 작업을 요청하지 않음
UNCHECKED: 동작 응답이 확인되지 않거나 응답 미수락
ERROR: 검증 실행에 오류 발생
VALID: 검증 결과가 유효함
INVALID: 검증 결과가 유효하지 않음

UNCHECKED,ERROR,INVALID는 유효성 검사 실패로 표시됨
validationResult.message string Validation 세부 메시지로 항상 표시되는 값은 아님
combineResult JSON object 판독 결과 결합
combineResult.name string 결합 필드 이름
combineResult.text string 각 필드별 출력값 및 고정 텍스트

2. ImageField 객체 필드

필드명 유형 설명
name string 요청 바디의 images.name에 입력한 이미지명
valueType string 필드의 텍스트 값 유형을 나타내며 텍스트 유형에 따라 표시되지 않을 수 있음
ALL: 텍스트와 숫자
inferText string 인식된 텍스트 값
inferConfidence float 인식한 텍스트에 대한 신뢰도를 0~1 사이로 나타내며 값이 클수록 정확도가 높음
boundingPoly JSON array object boundingPoly 객체 참조

API 예제

다음은 각 언어별 CLOVA OCR 구현 예제입니다

multipart/form-data 요청 예제

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
 
import org.json.JSONArray;
import org.json.JSONObject;
 
public class OCRGeneralAPIDemo {
 
    public static void main(String[] args) {
        String apiURL = "YOUR_API_URL";
        String secretKey = "YOUR_SECRET_KEY";
        String imageFile = "YOUR_IMAGE_FILE";
 
        try {
            URL url = new URL(apiURL);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setUseCaches(false);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setReadTimeout(30000);
            con.setRequestMethod("POST");
            String boundary = "----" + UUID.randomUUID().toString().replaceAll("-", "");
            con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            con.setRequestProperty("X-OCR-SECRET", secretKey);
 
            JSONObject json = new JSONObject();
            json.put("version", "V2");
            json.put("requestId", UUID.randomUUID().toString());
            json.put("timestamp", System.currentTimeMillis());
            JSONObject image = new JSONObject();
            image.put("format", "jpg");
            image.put("name", "demo");
            JSONArray images = new JSONArray();
            images.put(image);
            json.put("images", images);
            String postParams = json.toString();
 
            con.connect();
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            long start = System.currentTimeMillis();
            File file = new File(imageFile);
            writeMultiPart(wr, postParams, file, boundary);
            wr.close();
 
            int responseCode = con.getResponseCode();
            BufferedReader br;
            if (responseCode == 200) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            } else {
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
 
            System.out.println(response);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
 
    private static void writeMultiPart(OutputStream out, String jsonMessage, File file, String boundary) throws
        IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("--").append(boundary).append("\r\n");
        sb.append("Content-Disposition:form-data; name=\"message\"\r\n\r\n");
        sb.append(jsonMessage);
        sb.append("\r\n");
 
        out.write(sb.toString().getBytes("UTF-8"));
        out.flush();
 
        if (file != null && file.isFile()) {
            out.write(("--" + boundary + "\r\n").getBytes("UTF-8"));
            StringBuilder fileString = new StringBuilder();
            fileString
                .append("Content-Disposition:form-data; name=\"file\"; filename=");
            fileString.append("\"" + file.getName() + "\"\r\n");
            fileString.append("Content-Type: application/octet-stream\r\n\r\n");
            out.write(fileString.toString().getBytes("UTF-8"));
            out.flush();
 
            try (FileInputStream fis = new FileInputStream(file)) {
                byte[] buffer = new byte[8192];
                int count;
                while ((count = fis.read(buffer)) != -1) {
                    out.write(buffer, 0, count);
                }
                out.write("\r\n".getBytes());
            }
 
            out.write(("--" + boundary + "--\r\n").getBytes("UTF-8"));
        }
        out.flush();
    }
}
import requests
import uuid
import time
import json
 
api_url = 'YOUR_API_URL'
secret_key = 'YOUR_SECRET_KEY'
image_file = 'YOUR_IMAGE_FILE'
 
request_json = {
    'images': [
        {
            'format': 'jpg',
            'name': 'demo'
        }
    ],
    'requestId': str(uuid.uuid4()),
    'version': 'V2',
    'timestamp': int(round(time.time() * 1000))
}
 
payload = {'message': json.dumps(request_json).encode('UTF-8')}
files = [
  ('file', open(image_file,'rb'))
]
headers = {
  'X-OCR-SECRET': secret_key
}
 
response = requests.request("POST", api_url, headers=headers, data = payload, files = files)
 
print(response.text.encode('utf8'))
 
<?php
  $client_secret = "YOUR_SECRET_KEY";
  $url = "YOUR_API_URL";
  $image_file = "YOUR_IMAGE_FILE";
 
  $params->version = "V2";
  $params->requestId = uniqid();
  $params->timestamp = time();
  $image->format = "jpg";
  $image->name = "demo";
  $images = array($image);
  $params->images = $images;
  $json = json_encode($params);
   
  $boundary = uniqid();
  $is_post = true;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, $is_post);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $post_form = array("message" => $json, "file" => new CURLFILE($image_file));
  curl_setopt($ch, CURLOPT_POSTFIELDS, $post_form);
  $headers = array();
  $headers[] = "X-OCR-SECRET: ".$client_secret;
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  $response = curl_exec($ch);
  $err = curl_error($ch);
  $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close ($ch);
 
  echo $status_code;
  if($status_code == 200) {
    echo $response;
  } else {
    echo "ERROR: ".$response;
  }
?>
const FormData = require('form-data')
const axios = require('axios')
 
function requestWithBase64 () {
  axios
    .post(
      '', // APIGW Invoke URL
      {
        images: [
          {
            format: '', // file format
            name: '', // image name
            data: '' // image base64 string(only need part of data). Example: base64String.split(',')[1]
          }
        ],
        requestId: '', // unique string
        timestamp: 0,
        version: 'V2'
      },
      {
        headers: {
          'X-OCR-SECRET': '' // Secret Key
        }
      }
    )
    .then(res => {
      if (res.status === 200) {
        console.log('requestWithBase64 response:', res.data)
      }
    })
    .catch(e => {
      console.warn('requestWithBase64 error', e.response)
    })
}
 
function requestWithFile () {
  const file = '' // image file object. Example: fs.createReadStream('./example.png')
  const message = {
    images: [
      {
        format: '', // file format
        name: '' // file name
      }
    ],
    requestId: '', // unique string
    timestamp: 0,
    version: 'V2'
  }
  const formData = new FormData()
 
  formData.append('file', file)
  formData.append('message', JSON.stringify(message))
 
  axios
    .post(
      '', // APIGW Invoke URL
      formData,
      {
        headers: {
          'X-OCR-SECRET': '', // Secret Key
          ...formData.getHeaders()
        }
      }
    )
    .then(res => {
      if (res.status === 200) {
        console.log('requestWithFile response:', res.data)
      }
    })
    .catch(e => {
      console.warn('requestWithFile error', e.response)
    })
}

application/json 요청 예제

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
 
import org.json.JSONArray;
import org.json.JSONObject;
 
public class OCRGeneralAPIDemo {
 
    public static void main(String[] args) {
        String apiURL = "YOUR_API_URL";
        String secretKey = "YOUR_SECRET_KEY";
 
        try {
            URL url = new URL(apiURL);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.setUseCaches(false);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            con.setRequestProperty("X-OCR-SECRET", secretKey);
 
            JSONObject json = new JSONObject();
            json.put("version", "V2");
            json.put("requestId", UUID.randomUUID().toString());
            json.put("timestamp", System.currentTimeMillis());
            JSONObject image = new JSONObject();
            image.put("format", "jpg");
            image.put("url", "https://kr.object.ncloudstorage.com/ocr-ci-test/sample/1.jpg"); // image should be public, otherwise, should use data
            // FileInputStream inputStream = new FileInputStream("YOUR_IMAGE_FILE");
            // byte[] buffer = new byte[inputStream.available()];
            // inputStream.read(buffer);
            // inputStream.close();
            // image.put("data", buffer);
            image.put("name", "demo");
            JSONArray images = new JSONArray();
            images.put(image);
            json.put("images", images);
            String postParams = json.toString();
 
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(postParams);
            wr.flush();
            wr.close();
 
            int responseCode = con.getResponseCode();
            BufferedReader br;
            if (responseCode == 200) {
                br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            } else {
                br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
            }
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = br.readLine()) != null) {
                response.append(inputLine);
            }
            br.close();
 
            System.out.println(response);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
 
}
 
import requests
import uuid
import time
import base64
import json
 
api_url = 'YOUR_API_URL'
secret_key = 'YOUR_SECRET_KEY'
image_url = 'YOUR_IMAGE_URL'
# image_file = 'YOUR_IMAGE_FILE'
# with open(image_file,'rb') as f:
#     file_data = f.read()
 
request_json = {
    'images': [
        {
            'format': 'jpg',
            'name': 'demo',
#             'data': base64.b64encode(file_data).decode()
            'url': image_url
        }
    ],
    'requestId': str(uuid.uuid4()),
    'version': 'V2',
    'timestamp': int(round(time.time() * 1000))
}
 
payload = json.dumps(request_json).encode('UTF-8')
headers = {
  'X-OCR-SECRET': secret_key,
  'Content-Type': 'application/json'
}
 
response = requests.request("POST", api_url, headers=headers, data = payload)
 
print(response.text)
 
<?php
  $client_secret = "YOUR_SECRET_KEY";
  $url = "YOUR_API_URL";
  $image_url = "YOUR_IMAGE_URL";
  // $image_file = "YOUR_IMAGE_FILE";
 
  $params->version = "V2";
  $params->requestId = "uuid";
  $params->timestamp = time();
  $image->format = "jpg";
  $image->url = $image_url;
  // $image->data = base64_encode(file_get_contents($image_file));
  $image->name = "demo";
  $images = array($image);
  $params->images = $images;
  $json = json_encode($params);
 
  $is_post = true;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, $is_post);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
  $headers = array();
  $headers[] = "X-OCR-SECRET: ".$client_secret;
  $headers[] = "Content-Type:application/json; charset=utf-8";
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  $response = curl_exec($ch);
  $err = curl_error($ch);
  $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close ($ch);
 
  echo $status_code;
  if($status_code == 200) {
    echo $response;
  } else {
    echo "ERROR: ".$response;
  }
?>
 
<%
Function ASPPostJSON()
    Dim objXmlHttp
    Set objXmlHttp = Server.CreateObject("Microsoft.XMLHTTP")
    url = "YOUR_INVOKE_URL"
    secret = "YOUR_SECRET_KEY"
    base64 = """"+ToBase64(getBinaryFile(Server.MapPath("test.jpg")))+""""
    body = "{""images"":[{""format"":""jpg"",""name"":""test 1"",""data"":"+base64+"}],""requestId"":""string"",""timestamp"":0,""version"":""V2"",""lang"":""ko""}"
    objXmlHttp.Open "POST", url, False
    objXmlHttp.SetRequestHeader "Content-Type", "application/json"
    objXmlHttp.SetRequestHeader "X-OCR-SECRET", secret
 
    objXmlHttp.Send body
 
    ASPPostJSON = CStr(objXmlHttp.ResponseText)
 
    Response.write(ASPPostJSON)
    Set objXmlHttp = Nothing
 
End Function
 
Function getBinaryFile(strFilePath)
  Dim TypeBinary, oStream
 
  TypeBinary = 1
 
  Set oStream = Server.CreateObject("ADODB.Stream")
 
  oStream.Open
 
  oStream.Type = TypeBinary
  oStream.LoadFromFile strFilePath
 
  getBinaryFile = oStream.read
 
  Set oStream = Nothing
 
End Function
 
Function ToBase64(rabyt)
 
     Dim xml: Set xml = CreateObject("MSXML2.DOMDocument.3.0")
     xml.LoadXml "<root />"
     xml.documentElement.dataType = "bin.base64"
     xml.documentElement.nodeTypedValue = rabyt
 
     ToBase64 = xml.documentElement.Text
 
End Function
 
call ASPPostJSON()
%>