첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
------------------------------------------------------------------------------------------------------------------------------------------------------
728x90
728x170

■ Bitmap 클래스를 사용해 투명 비트맵을 구하는 방법을 보여준다.

 

▶ 예제 코드 (C#)

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

#region 투명 비트맵 구하기 - GetTransparentBitmap(sourceImage, alpha)

/// <summary>
/// 투명 비트맵 구하기
/// </summary>
/// <param name="sourceImage">소스 이미지</param>
/// <param name="alpha">알파</param>
/// <returns>투명 비트맵</returns>
public Bitmap GetTransparentBitmap(Image sourceImage, byte alpha = 100)
{
    Bitmap targetBitmap = GetBitmap(sourceImage);

    BitmapData targetBitmapData = targetBitmap.LockBits
    (
        new Rectangle(0, 0, sourceImage.Width, sourceImage.Height),
        ImageLockMode.ReadOnly,
        PixelFormat.Format32bppArgb
    );

    IntPtr sourceHandle = targetBitmapData.Scan0;

    byte[] targetByteArray = new byte[targetBitmapData.Stride * targetBitmap.Height];

    Marshal.Copy(sourceHandle, targetByteArray, 0, targetByteArray.Length);

    for(int i = 3; i < targetByteArray.Length; i += 4)
    {
        targetByteArray[i] = alpha;
    }

    Marshal.Copy(targetByteArray, 0, sourceHandle, targetByteArray.Length);

    targetBitmap.UnlockBits(targetBitmapData);

    targetBitmapData = null;
    targetByteArray  = null;

    return targetBitmap;
}

#endregion
#region 비트맵 구하기 - GetBitmap(sourceImage)

/// <summary>
/// 비트맵 구하기
/// </summary>
/// <param name="sourceImage">소스 이미지</param>
/// <returns>비트맵</returns>
private Bitmap GetBitmap(Image sourceImage)
{
    Bitmap targetBitmap = new Bitmap
    (
        sourceImage.Width,
        sourceImage.Height,
        PixelFormat.Format32bppArgb
    );

    using(Graphics graphics = Graphics.FromImage(targetBitmap))
    {
        graphics.DrawImage
        (
            sourceImage,
            new Rectangle(0, 0, targetBitmap.Width, targetBitmap.Height),
            new Rectangle(0, 0, targetBitmap.Width, targetBitmap.Height),
            GraphicsUnit.Pixel
        );

        graphics.Flush();
    }

    return targetBitmap;
}

#endregion
728x90
그리드형(광고전용)
Posted by icodebroker
,