C# Сохраненное изображение просто полностью черное? - PullRequest
0 голосов
/ 02 апреля 2020

Когда я пытался сохранить изображение формы, нажав кнопку экспорта, я получаю полностью черное изображение. Я пробовал PNG, JPEG.

private void exportButton_Click(object sender, RoutedEventArgs e)
{
    ScreenShot.CaptureImage(this.Location, new System.Drawing.Point(Convert.ToInt32(this.Location.X) + Convert.ToInt32(this.Width) , Convert.ToInt32(this.Location.Y)  + Convert.ToInt32(this.Height)), new Rectangle(this.Location.X, this.Location.Y, Convert.ToInt32(this.Width) , Convert.ToInt32(this.Height)), @"C:\Users\Jens\Desktop\test.Bmp");
}

Класс, которым я пользуюсь:

public static void CaptureImage(Point SourcePoint, Point DestinationPoint, Rectangle SelectionRectangle, string FilePath)
{
    using (Bitmap bitmap = new Bitmap(SelectionRectangle.Width, SelectionRectangle.Height))
    {
        using (Graphics g = Graphics.FromImage(bitmap))
        {
            g.CopyFromScreen(SourcePoint, DestinationPoint, SelectionRectangle.Size);
        }
        bitmap.Save(FilePath, ImageFormat.Bmp);
    }
}

1 Ответ

0 голосов
/ 02 апреля 2020

Это было нелегко. Ниже приведен рабочий пример с использованием WPF и WinForms.

Я обнаружил, что при масштабировании дисплея в соответствии с настройками ОС он начинает работать при работе с необработанной графикой (относительно координат / размеров). enter image description here В примере WPF я назвал это SCALE_FACTOR. Поскольку моя шкала windows установлена ​​на 150%, я масштабируюсь с коэффициентом 1.5. Пример WPF работает тогда для меня:

Пример WPF:

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private const double SCALE_FACTOR = 1.5; // 150% in windows 10 settings

    private void button_Click(object sender, RoutedEventArgs e)
    {
        // take window location
        var x = (int)(Application.Current.MainWindow.Left);
        var y = (int)(Application.Current.MainWindow.Top);
        // convert to System.Drawing.Point
        var currentLocationPoint = new System.Drawing.Point(x, y);
        CaptureImage(
            // current TOP, LEFT location of the window on the screen
            currentLocationPoint, 
            // TOP, LEFT location of the destination
            new System.Drawing.Point(0, 0), 
            // size of the current window AND of the destination window/buffer/image
            new System.Drawing.Rectangle(
                0, 
                0, 
                // need to scale the width because of the OS scaling
                (int)(this.ActualWidth * SCALE_FACTOR),
                // need to scale the heigt because of the OS scaling
                (int)(this.ActualHeight * SCALE_FACTOR)), 
            @"c:\temp\screen.bmp");
    }

    public static void CaptureImage(System.Drawing.Point SourcePoint, System.Drawing.Point DestinationPoint, System.Drawing.Rectangle SelectionRectangle, string FilePath)
    {
        // create new image with the specified size = current window size
        using (Bitmap bitmap = new Bitmap(SelectionRectangle.Width, SelectionRectangle.Height))
        {
            using (Graphics g = Graphics.FromImage(bitmap))
            {
                g.CopyFromScreen(
                    // X start for copy is current window LEFT - scaled
                    (int)(SourcePoint.X * SCALE_FACTOR), 
                    // Y start for copy is current window TOP - scaled
                    (int)(SourcePoint.Y * SCALE_FACTOR), 
                    // X start in destination window is 0
                    0, 
                    // Y start in destination window is 0
                    0, 
                    // size of destination window is the same as the current window
                    SelectionRectangle.Size);
            }
            bitmap.Save(FilePath, ImageFormat.Bmp);
        }
    }
}

Windows Пример форм:

В моем тесте windows имеет размер (250,250) в пикселях.

SourcePoint - начало, поэтому оно должно быть на самом деле (0,0). DestinationSize - это высота и ширина - вам не нужны преобразования.

    //CaptureImage(this.Location, new Point(0, 0), new Rectangle(0, 0, 250, 250), @"c:\temp\screen.bmp");
    CaptureImage(this.Location, new System.Drawing.Point(0, 0), new Rectangle(this.Location.X, this.Location.Y, this.Width , this.Height),@"c:\temp\screen.bmp");

enter image description here

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...