2024/05/26(Sun) 18:45:04 編集(投稿者)
■No103125 (紅 さん) に返信
> しかし、PNGファイルだと左右で違うパレットのため片方の画像が正常に表示できません。
フルカラーにしてから合成すればよいのでは?
モノクロビットマップとフルカラービットマップでテストしました。
static void Main(string[] args) {
var left = new BitmapImage(new Uri(@"z:\mono.bmp"));
var right = new BitmapImage(new Uri(@"z:\fullcolor.bmp"));
var writeableBitmap = Combine(left, right);
using (FileStream fileStream = new FileStream(@"z:\003.png", FileMode.Create)) {
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(writeableBitmap));
encoder.Save(fileStream);
}
}
public static WriteableBitmap Combine(BitmapImage left, BitmapImage right) {
var width = left.PixelWidth + right.PixelWidth;
var height = Math.Max(left.PixelHeight, right.PixelHeight);
var wb = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);
WriteImage(wb, left, 0, 0);
WriteImage(wb, right, left.PixelWidth, 0);
if (wb.CanFreeze) wb.Freeze();
return wb;
}
static void WriteImage(WriteableBitmap destination, BitmapImage source, int x, int y) {
source = ConvertPixelFormat(source, destination.Format);
int stride = (source.PixelWidth * source.Format.BitsPerPixel + 7) / 8;
byte[] pixels = new byte[source.PixelHeight * stride];
source.CopyPixels(new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight), pixels, stride, 0);
destination.WritePixels(new Int32Rect(x, y, source.PixelWidth, source.PixelHeight), pixels, stride, 0);
}
static BitmapImage ConvertPixelFormat(BitmapImage source, PixelFormat pixelFormat) {
if (source.Format == pixelFormat) {
return source;
}
var formatter = new FormatConvertedBitmap();
formatter.BeginInit();
formatter.Source = source;
formatter.DestinationFormat = pixelFormat;
formatter.EndInit();
using (MemoryStream memoryStream = new MemoryStream()) {
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(formatter));
encoder.Save(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);
BitmapImage converted = new BitmapImage();
converted.BeginInit();
converted.StreamSource = memoryStream;
converted.CacheOption = BitmapCacheOption.OnLoad;
converted.EndInit();
return converted;
}
}