C#实现:基于背景图与二维码图生成指定位置的新图片
C# Image Composition: Background + Positioned QR Code
No problem! Below is a practical, reusable C# function that lets you merge your background image with a QR code, with full control over where the QR code is placed on the final image.
Step 1: Prerequisites
First, make sure you have the System.Drawing.Common NuGet package installed (required for .NET Core/.NET 5+; .NET Framework has this built-in).
Step 2: Complete Implementation
using System.Drawing; using System.Drawing.Imaging; public static class ImageComposer { /// <summary> /// Combines a background image with a QR code at a specified position /// </summary> /// <param name="backgroundPath">File path to the background image</param> /// <param name="qrCodePath">File path to the QR code image</param> /// <param name="qrPosition">Position (X,Y coordinates) where the QR code should be placed</param> /// <param name="outputPath">File path to save the composed image</param> /// <param name="imageFormat">Output image format (default: PNG)</param> public static void CombineImages(string backgroundPath, string qrCodePath, Point qrPosition, string outputPath, ImageFormat imageFormat = null) { // Use using statements to automatically dispose of image resources and avoid memory leaks using (var backgroundImage = Image.FromFile(backgroundPath)) using (var qrCodeImage = Image.FromFile(qrCodePath)) using (var composedImage = new Bitmap(backgroundImage.Width, backgroundImage.Height)) using (var graphics = Graphics.FromImage(composedImage)) { // Draw the background image first (covers the entire canvas) graphics.DrawImage(backgroundImage, new Rectangle(0, 0, composedImage.Width, composedImage.Height)); // Draw the QR code at your specified X/Y coordinates // Use the QR code's original size by default graphics.DrawImage(qrCodeImage, qrPosition.X, qrPosition.Y); // Fall back to PNG if no format is provided imageFormat ??= ImageFormat.Png; // Save the final combined image to your desired path composedImage.Save(outputPath, imageFormat); } } }
How to Use It
Call the function in your code like this (adjust paths and position to match your needs):
// Example: Place QR code at X=50, Y=100 on the background image ImageComposer.CombineImages( @"C:\assets\background.jpg", @"C:\assets\qrcode.png", new Point(50, 100), @"C:\output\final_image.png" );
Customization Tips
- Resize QR Code: If you need to adjust the QR code's dimensions, replace the QR code
DrawImagecall with this (example resizes to 150x150 pixels):graphics.DrawImage(qrCodeImage, new Rectangle(qrPosition.X, qrPosition.Y, 150, 150)); - Transparent QR Codes: The function works seamlessly with transparent PNG QR codes—no extra configuration needed.
- Error Handling: Add try-catch blocks to handle edge cases like missing files or invalid image formats, depending on your application's requirements.
内容的提问来源于stack exchange,提问作者Claudio Gareca
相关产品推荐
相关产品推荐

