-1

I'm working with C#, só I start one "Windows Form application" in order to use the "picturebox", where I can draw some things. I would like to know if there's a way to save a file in some kind of file (like JPG). Here's an example, where I draw a simple line in a pictureBox with 300 of Height and 300 of Width.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AskStack
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // Here I declare 'MyDraw' and a Pen that I'm gonna use
        Graphics MyDraw;
        Pen BluePen = new Pen(Color.Blue, 10);

        // What happens when I click in my button
        private void ButtonDraw_Click(object sender, EventArgs e)
        {
            MyDraw.Clear(Color.White);

            // Here I relate MyDraw to the pictureBox that I have in my Form
            MyDraw = pictureBox1.CreateGraphics();

            // Here I Just draw a simple line
            MyDraw.DrawLine(BluePen, 25, 25, 80, 80);

            // I don't know exactly what this does
            MyDraw.Save();
        }
    }
}

I would like to know if there's a way to save this image in a file where I can easily acess it. Also, I would like to know if there's a way to save an JPG file and dimension the file's size WITHOUT using a pictureBox. Thanks!!!

  • 1
    You should peruse the many, many posts here on drawing. Do not store a graphics object nor Pens, do not use CreateGraphics and to save it, you want to draw to a bitmap. And always dispose of graphics objects you create – Ňɏssa Pøngjǣrdenlarp Aug 03 '18 at 20:50
  • Plutonix has it right. Your code is wrong in __many__ ways. One is that the things you draw can't be saved, except by making a screenshot. ((Btw: Saving a Graphics object stores its state, ie scaling, modes, translations, clipping etc.. all advanced stuff you don't need to worry about now..)) - You should draw in the Paint event; then you can save the things you draw with DrawToBitmap. Or draw into a Bitmap. See [here](https://stackoverflow.com/questions/27337825/picturebox-paintevent-with-other-method/27341797?s=3|20.7453#27341797) for examples for either way.. – TaW Aug 03 '18 at 22:06

1 Answers1

0

You can try with this line of code:

pictureBox1.Image.Save(@"Path",ImageFormat.Jpeg);
mororo
  • 1,074
  • 2
  • 11
  • 28