c# bitmap 예제

이번 예제에서는 C#의 Bitmap 클래스를 사용하여 이미지 파일을 로드하고, 픽셀 값을 변경하고, 저장하는 방법에 대해 알아보겠습니다.

이미지 로드하기

다음 예제 코드는 Bitmap 클래스의 FromFile 메서드를 사용하여 이미지 파일을 로드하는 방법을 보여줍니다.

using System;
using System.Drawing;

class Program
{
    static void Main(string[] args)
    {
        string filePath = "image.jpg"; // 로드할 이미지 파일 경로
        Bitmap bitmap = new Bitmap(filePath);

        // 이미지 정보 출력
        Console.WriteLine($"이미지 크기: {bitmap.Width} x {bitmap.Height}");
        Console.WriteLine($"픽셀 형식: {bitmap.PixelFormat}");

        // 추가적인 작업 수행 가능

        bitmap.Dispose(); // 이미지 리소스 해제
    }
}

픽셀 값 변경하기

다음 예제 코드는 Bitmap 클래스의 SetPixel 메서드를 사용하여 이미지의 특정 좌표에 있는 픽셀 값을 변경하는 방법을 보여줍니다.

using System;
using System.Drawing;

class Program
{
    static void Main(string[] args)
    {
        string filePath = "image.jpg"; // 이미지 파일 경로
        Bitmap bitmap = new Bitmap(filePath);

        int x = 100; // 변경할 픽셀의 x 좌표
        int y = 200; // 변경할 픽셀의 y 좌표
        Color newColor = Color.Red; // 변경할 픽셀의 새로운 색상

        bitmap.SetPixel(x, y, newColor); // 픽셀 값 변경

        bitmap.Save("modified_image.jpg"); // 변경된 이미지 저장

        bitmap.Dispose(); // 이미지 리소스 해제
    }
}

이미지 저장하기

다음 예제 코드는 Bitmap 클래스의 Save 메서드를 사용하여 이미지 파일을 저장하는 방법을 보여줍니다.

using System;
using System.Drawing;

class Program
{
    static void Main(string[] args)
    {
        string filePath = "image.jpg"; // 이미지 파일 경로
        Bitmap bitmap = new Bitmap(filePath);

        // 이미지 변경 작업 수행

        string savePath = "modified_image.jpg"; // 저장할 이미지 파일 경로
        bitmap.Save(savePath); // 이미지 저장

        Console.WriteLine($"변경된 이미지가 {savePath}에 저장되었습니다.");

        bitmap.Dispose(); // 이미지 리소스 해제
    }
}

이 예제 코드를 참고하여 C#의 Bitmap 클래스를 사용하는 방법을 익히면, 이미지 파일을 조작하고 처리하는 다양한 작업을 수행할 수 있습니다.

#CSharp #Bitmap