using DesktopTools.Interfaces;
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace DesktopTools.BaseControls
{
///
/// Контрол, предоставляющий работу с изображением
///
public partial class BaseControlImage : AbstractBaseControl, IBaseControl
{
///
/// Конструктор
///
///
///
///
///
///
public BaseControlImage(string propertyName, bool mustFilling, bool readOnly, int width, int height) : base(propertyName, mustFilling, readOnly)
{
InitializeComponent();
_baseControl = this;
if (width != 0)
{
Width = width;
}
if (height != 0)
{
Height = height;
}
buttonLoad.Click += (object sender, EventArgs e) =>
{
var dialog = new OpenFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
pictureBox.ClientSize = new Size(150, 150);
pictureBox.Image = new Bitmap(dialog.FileName);
CallOnValueChangeEvent();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке файла", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
};
panelControl.Controls.Add(pictureBox);
panelControl.Controls.Add(buttonLoad);
}
public void SetDefaultValue() => _originalValue = null;
public void SetValueToControl(object value)
{
if (value != null && (value as byte[])?.Length > 0)
{
using MemoryStream mStream = new(value as byte[]);
pictureBox.Image = Image.FromStream(mStream);
}
else if (!_mustFilling)
{
pictureBox.Image = null;
}
}
public void DropValueForControl()
{
if (_originalValue != null)
{
using MemoryStream mStream = new(_originalValue as byte[]);
pictureBox.Image = Image.FromStream(mStream);
}
else if (!_mustFilling)
{
pictureBox.Image = null;
}
}
public bool CheckValueForControl()
{
if (_mustFilling && pictureBox.Image == null)
{
BackColor = Color.OrangeRed;
return false;
}
return true;
}
public object GetValueFromControl()
{
if (_mustFilling && pictureBox.Image == null)
{
throw new ArgumentNullException($"Поле свойства '{labelTitle.Text}' должно быть заполнено");
}
var converter = new ImageConverter();
return (byte[])converter.ConvertTo(new Bitmap(pictureBox.Image), typeof(byte[]));
}
public string GetPropertyName() => _propertyName;
}
}