1.使用 TransformedBitmap 类(System.Windows.Media.Imaging)可以对图片进行缩放操作。

var originalBitmap = new BitmapImage(new Uri("yourImagePath"));

// 缩放图片
var scaleTransform = new ScaleTransform(0.5, 0.5); // 缩放比例:50%
var scaledBitmap = new TransformedBitmap(originalBitmap, scaleTransform);

// 旋转图片
var rotateTransform = new RotateTransform(45); // 旋转45度
var transformedBitmap = new TransformedBitmap(scaledBitmap, rotateTransform);

// 设置图片源
imageControl.Source = transformedBitmap;

// 设置透明度
imageControl.Opacity = 0.5; // 透明度设置为50%

2.System.Drawing (GDI+)

public static Bitmap ModifyImage(string imagePath, double newWidth, double newHeight, double rotationAngle, double stampTransparency, bool isCircle)
{
    // 加载图像
    Bitmap image = new Bitmap(imagePath);

    // 修改图像大小
    Bitmap resizedImage = new Bitmap((int)Math.Round(newWidth), (int)Math.Round(newHeight));

    using (Graphics g = Graphics.FromImage(resizedImage))
    {
        // 设置高质量插值法和抗锯齿模式
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;

        // 绘制缩放后的图像
        g.DrawImage(image, 0, 0, resizedImage.Width, resizedImage.Height);
    }

    Bitmap finalImage;

    // 仅保留圆形处理的代码
    if (isCircle)
    {
        finalImage = new Bitmap(resizedImage.Width, resizedImage.Height, PixelFormat.Format32bppArgb);

        using (Graphics g = Graphics.FromImage(finalImage))
        {
            // 清除背景(透明)
            g.Clear(Color.Transparent);

            // 设置旋转中心为图像的中心
            g.TranslateTransform((float)resizedImage.Width / 2, (float)resizedImage.Height / 2);

            // 旋转图像
            g.RotateTransform((float)-rotationAngle);

            // 重置变换矩阵回原点
            g.TranslateTransform(-(float)resizedImage.Width / 2, -(float)resizedImage.Height / 2);

            // 绘制图像
            g.DrawImage(resizedImage, new Point(0, 0));
        }
    }

    // 设置透明度
    if (stampTransparency >= 0)
    {
        // 创建一个新的位图,用于保存透明度应用后的图像
        Bitmap transparentImage = new Bitmap(finalImage.Width, finalImage.Height, PixelFormat.Format32bppArgb);

        using (Graphics g = Graphics.FromImage(transparentImage))
        {
            // 使用颜色矩阵应用透明度
            ColorMatrix colorMatrix = new ColorMatrix
            {
                Matrix33 = (float)(stampTransparency / 100.0f) // 设置Alpha值
            };
            ImageAttributes attributes = new ImageAttributes();
            attributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            // 绘制图像,并应用透明度
            g.DrawImage(finalImage, new Rectangle(0, 0, finalImage.Width, finalImage.Height),
                        0, 0, finalImage.Width, finalImage.Height, GraphicsUnit.Pixel, attributes);
        }

        finalImage.Dispose(); // 释放旧的图像资源
        finalImage = transparentImage; // 用透明度应用后的图像替换
    }

    return finalImage;
}

标签: none

添加新评论