CAD 도면을 작업할 때는 종종 DWG 파일을 PNG와 같은 웹 친화적인 이미지로 변환해야 합니다. Aspose.BarCode Cloud SDK for Python은 처리를 클라우드에 오프로드함으로써 이 변환을 간단하게 만들어 줍니다. 이 튜토리얼에서는 SDK 설정, 인증, DWG를 PNG로 변환하는 Python 코드를 작성하는 방법과 raw cURL 요청으로 동일한 결과를 얻는 방법을 보여드리며, 이를 통해 Python 애플리케이션에 DWG 렌더링을 손쉽게 통합할 수 있습니다.

Python에서 DWG를 PNG로 변환 - 단계

  1. 자격 증명 구성: SDK가 Aspose 클라우드와 인증할 수 있도록 클라이언트 ID와 클라이언트 비밀을 설정합니다.
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"
  1. API 클라이언트 초기화: Configuration 객체를 생성하고, 자격 증명을 할당한 다음 ApiClientBarcodeApi 인스턴스를 빌드합니다.
config = Configuration()
config.client_id = client_id
config.client_secret = client_secret

api_client = ApiClient(configuration=config)
barcode_api = BarcodeApi(api_client)
  1. Read the DWG File: 소스 DWG 파일을 바이너리 모드로 열고 내용을 메모리로 읽어옵니다.
with open("sample.dwg", "rb") as file_stream:
    dwg_bytes = file_stream.read()
  1. 변환 엔드포인트 호출: convert_image를 사용하고 대상 형식으로 "png"를 지정합니다. 이 메서드는 PNG 데이터를 바이트 배열로 반환합니다.
conversion_response = barcode_api.convert_image(
    file=dwg_bytes,
    format="png"
)
  1. PNG 출력 저장: 반환된 바이트를 .png 확장자를 가진 파일에 씁니다.
with open("sample.png", "wb") as out_file:
    out_file.write(conversion_response)

convert_image 메서드에 대한 자세한 내용은 API 참조를 확인하십시오.

Python에서 DWG를 PNG로 변환 - 전체 작업 샘플

다음 예제는 Python에서 Aspose.BarCode Cloud SDK를 사용하여 DWG를 PNG로 변환하는 전체 워크플로를 보여줍니다.

import os
from asposebarcodecloud import Configuration, ApiClient, BarcodeApi, ApiException

# -------------------- Configuration --------------------
# Replace with your actual Aspose.BarCode Cloud credentials
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"

config = Configuration()
config.client_id = client_id
config.client_secret = client_secret

# Initialize API client
api_client = ApiClient(configuration=config)
barcode_api = BarcodeApi(api_client)

# -------------------- File Paths --------------------
input_path = "sample.dwg"      # Path to the source DWG file
output_path = "sample.png"     # Desired PNG output path

# -------------------- Conversion --------------------
try:
    # Read the DWG file into memory
    with open(input_path, "rb") as file_stream:
        dwg_bytes = file_stream.read()

# The Aspose.BarCode Cloud SDK provides a generic image conversion endpoint.
    # Here we invoke it, specifying the target format as PNG.
    # The method name and parameters are based on the SDK's conversion API.
    conversion_response = barcode_api.convert_image(
        file=dwg_bytes,          # Binary content of the DWG file
        format="png"             # Target image format
    )

# Write the resulting PNG bytes to the output file
    with open(output_path, "wb") as out_file:
        out_file.write(conversion_response)

print(f"Conversion successful: '{input_path}' → '{output_path}'")

except ApiException as api_err:
    print(f"API error during conversion: {api_err}")
except Exception as err:
    print(f"Unexpected error: {err}")
finally:
    # Explicitly close the API client session if needed
    if hasattr(api_client, "close"):
        api_client.close()

Note: 이 코드 예제는 핵심 기능을 보여줍니다. 프로젝트에서 사용하기 전에 파일 경로와 구성 값을 실제 환경에 맞게 업데이트하고, 모든 필수 종속성이 올바르게 설치되었는지 확인하며, 개발 환경에서 충분히 테스트하십시오. 문제가 발생하면 공식 문서를 참조하거나 지원 팀에 문의하십시오.

cURL을 사용한 REST API로 DWG를 PNG로 변환

아래는 REST 인터페이스를 사용하여 동일한 변환을 수행하는 일련의 cURL 명령입니다.

  1. 액세스 토큰 얻기
curl -X POST "https://api.aspose.cloud/connect/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"

응답에 access_token이 포함됩니다.

  1. DWG 파일 업로드
curl -X PUT "https://api.aspose.cloud/v3.0/barcode/storage/file/sample.dwg" \
        -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
        -H "Content-Type: application/octet-stream" \
        --data-binary "@sample.dwg"
  1. 변환 실행
curl -X POST "https://api.aspose.cloud/v3.0/barcode/convert?format=png" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/octet-stream" \
     --data-binary "@sample.dwg" \
     -o sample.png
  1. PNG 결과 다운로드 (위에서 -o를 사용한 경우 선택 사항)
curl -X GET "https://api.aspose.cloud/v3.0/barcode/storage/file/sample.png" \
        -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
        -o sample.png

전체 매개변수 목록은 공식 API 문서를 참조하십시오.

설치 및 구성 Aspose.BarCode Cloud SDK for Python

SDK는 PyPI를 통해 배포됩니다. 다음 명령으로 설치하십시오:

pip install aspose-barcode-cloud

필수 조건: Python 3.6 이상, 활성화된 Aspose 계정, 그리고 유효한 클라이언트 자격 증명. SDK는 Aspose 클라우드 엔드포인트에 도달하기 위해 인터넷 액세스가 필요합니다.

패키지는 릴리스 페이지에서 직접 다운로드할 수도 있습니다.

DWG를 PNG로 변환하기 위한 매개변수 구성

변환 호출은 출력 이미지 유형을 결정하는 format 매개변수를 받습니다. 예제에서는 이를 "png" 로 설정했습니다:

conversion_response = barcode_api.convert_image(
    file=dwg_bytes,
    format="png"
)

다른 선택적 매개변수(예: outPath, storage 또는 이미지 품질 설정)는 API 참조에 문서화되어 있습니다. 프로젝트 요구 사항에 맞게 필요에 따라 조정하십시오.

결론

DWG를 PNG로 변환하는 작업은 Aspose.BarCode Cloud SDK for Python의 강력한 기능 덕분에 Python에서 매우 간단해집니다. 위의 단계를 따라 하면 벡터‑투‑래스터 변환을 모든 백엔드 서비스에 통합하고, 배치 처리를 자동화하거나 CAD 도면에 대한 온‑디맨드 미리보기를 생성할 수 있습니다. 개발 및 테스트를 위해서는 Aspose temporary license page에서 유효한 임시 라이선스를 확보하고, 운영 환경에서는 정식 라이선스 구매를 고려하십시오. 즐거운 코딩 되세요!

자주 묻는 질문

  • SDK가 변환을 지원하는 파일 형식은 무엇인가요?
    클라우드 변환 엔드포인트는 DWG를 포함한 다양한 벡터 및 래스터 형식을 처리하며, DXF, SVG, PDF 등도 지원합니다. 전체 목록은 문서를 참조하세요.

  • Python에서 DWG를 PNG로 변환하는 것이 스레드‑안전한가요?
    예, 각 BarcodeApi 인스턴스는 스레드당 별도의 자격 증명 객체를 관리하는 한 동시에 사용할 수 있습니다.

더 읽기