2014-04-02 36 views
1

我在我的应用程序中使用Windows.Control.Canvas来获取用户的签名。那么我只想将这个签名保存为jpeg图片。将canvas转换为jpeg图像颜色错误

但是,当我保存图片的颜色似乎是倒转 只是为了测试我也试图保存图片为PNG - 现在的图片是它应该是!

我使用这个代码来保存这些图片:

public static void SaveCanvasToJPEG(Canvas canvas) 
{ 
    Rect bounds = VisualTreeHelper.GetDescendantBounds(canvas); 
    RenderTargetBitmap rtb = new RenderTargetBitmap((int)(bounds.Width), 
                (int)(bounds.Height), 
                96d, 
                96d, 
                PixelFormats.Default); 

    DrawingVisual dv = new DrawingVisual(); 
    using (DrawingContext ctx = dv.RenderOpen()) 
    { 
     VisualBrush vb = new VisualBrush(canvas); 
     ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size)); 
    } 
    rtb.Render(dv); 

    //endcode as PNG 
    JpegBitmapEncoder jpegEncoder = new JpegBitmapEncoder(); 
    FormatConvertedBitmap convertImg2GrayScale = new FormatConvertedBitmap(rtb, PixelFormats.Gray16, null, 0); 
    jpegEncoder.Frames.Add(BitmapFrame.Create(convertImg2GrayScale)); 

    // *********** TESTING (begin) ************ 
    System.IO.MemoryStream ms2 = new System.IO.MemoryStream(); 
    PngBitmapEncoder pngEncoder = new PngBitmapEncoder(); 
    pngEncoder.Frames.Add(BitmapFrame.Create(rtb)); 
    pngEncoder.Save(ms2); 
    ms2.Close(); 
    System.IO.File.WriteAllBytes("logo.png", ms2.ToArray()); 
    // *********** TESTING (end) ************ 


    //save to memory stream 
    System.IO.MemoryStream ms = new System.IO.MemoryStream(); 

    jpegEncoder.Save(ms); 
    ms.Close(); 

    System.IO.File.WriteAllBytes("logo.jpg", ms.ToArray()); 
} 

的这里是XML:

<UserControl x:Class="WPF_App.SignControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="600" d:DesignWidth="1252" Loaded="_eventUserControlLoaded"> 
     <Grid> 
      <Grid.RowDefinitions> 
       <RowDefinition/> 
       <RowDefinition Height="0*"/> 
      </Grid.RowDefinitions> 
      <Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="330" Margin="159,149,0,0" VerticalAlignment="Top" Width="935"/> 
      <Canvas x:Name="canSignPad" Focusable="True" HorizontalAlignment="Left" Height="328" Margin="160,150,0,0" 
        ScrollViewer.VerticalScrollBarVisibility="Disabled" VerticalAlignment="Top" Width="933" 
        MouseDown="_canvasMouseDown" MouseMove="_canvasMouseMove"> 
       <Canvas.Background> 
        <SolidColorBrush Color="White" Opacity="0"/> 
       </Canvas.Background> 
      </Canvas> 
    </Grid> 
    </UserControl> 

我发现很多帖子谈论JPEG照片的问世蓝色的,但我没有找到我的问题的解决方案。

回答

0

我必须改变我的XAML定义:

<Canvas.Background> 
     <SolidColorBrush Color="White"/> 
    </Canvas.Background> 

不使用透明度=“0”当你想你的画布保存为JPEG - 原因JPEG不支持透明度