So I'm trying to create an application that displays all the cursors in the folder C:\Windows\Cursors and allows the user to click on an image of the cursor they want and have it applied. Thanks for reading.
I've been trying to convert the .cur file to .jpeg because I think this is the reason that it is not being displayed under flowLayoutPanel1 but it is still not working.
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using System.Windows.Forms;
using System.Drawing.Imaging;
using ImageMagick;
namespace CrossHare
{
public partial class Form1 : Form
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool SystemParametersInfo(int uiAction, int uiParam, IntPtr pvParam, int fWinIni);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr LoadCursorFromFile(string lpFileName);
private const int SPI_SETCURSORS = 0x0057;
private const int SPIF_UPDATEINIFILE = 0x01;
private const int SPIF_SENDCHANGE = 0x02;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Get the file paths of all files in the directory
string[] files = Directory.GetFiles(#"C:\Windows\Cursors");
// Iterate through the file paths
foreach (string file in files)
{
// Check if the file is an image file
if (!file.EndsWith(".cur")) continue;
try
{
// Create a new button
Button btn = new Button();
//Convert cur file to jpeg
using (MagickImage image = new MagickImage(file))
{
string jpegFile = Path.ChangeExtension(file, ".jpeg");
image.Format = MagickFormat.Jpeg;
image.Write(jpegFile);
using (Image img = Image.FromFile(jpegFile))
{
btn.Tag = file;
btn.Image = img;
}
}
btn.Size = new Size(100, 100);
btn.Click += Button_Click;
flowLayoutPanel1.Controls.Add(btn);
}
catch (FileNotFoundException ex)
{
// Handle file not found exception
MessageBox.Show("Error: " + ex.Message);
}
catch (OutOfMemoryException ex)
{
// Handle out of memory exception
MessageBox.Show("Error: " + ex.Message);
}
}
}
private void Button_Click(object sender, EventArgs e)
{
// Handle button click event
MessageBox.Show("Button clicked!");
// Get the selected file's path
string filePath = ((Button)sender).Image.Tag as string;
// Set the selected file as the "normal select" pointer in "Mouse properties"
RegistryKey key = Registry.CurrentUser.OpenSubKey("Control Panel\\Cursors", true);
key.SetValue("Arrow", filePath);
key.Close();
IntPtr hCursor = new IntPtr((int)LoadCursorFromFile(filePath));
SystemParametersInfo(SPI_SETCURSORS, 0, hCursor, SPIF_UPDATEINIFILE | SPIF_SENDCHANGE);
}
private void UploadButton_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Cursor files (*.cur)|*.cur|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
// Get the selected file's path
string filePath = openFileDialog.FileName;
// Do something with the file (e.g. upload it to a server)
string destinationPath = #"C:\Windows\Cursors";
string destinationFilePath = Path.Combine(destinationPath, Path.GetFileName(filePath));
if (File.Exists(destinationFilePath))
{
DialogResult result = MessageBox.Show("File already exists, do you want to overwrite it?", "File Exists", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
return;
}
}
File.Copy(filePath, destinationFilePath, true);
}
}
}
}
After carefully reading your code, if I'm following correctly your objectives are:
Display all the available cursors in a FlowLayoutPanel.
Click on an image to change the current cursor.
What we end up with here could be considered an X-Y Problem because doing that is straightforward, but the manner in which you're trying to solve your problem is not.
Please allow me to steer the conversation back to what you were trying to do to begin with:
To achieve this objective, use reflection to obtain the cursors from the Cursors class, draw each one, and place a corresponding button in the FlowLayoutPanel.
public partial class MainForm : Form
{
public MainForm()=>InitializeComponent();
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
foreach (PropertyInfo pi in typeof(Cursors).GetProperties(BindingFlags.Static | BindingFlags.Public))
{
if(pi.GetValue(null) is Cursor cursor)
{
var image = new Bitmap(100, 100);
using (var graphics = Graphics.FromImage(image))
{
cursor.DrawStretched(
graphics,
new Rectangle(new Point(), new Size(image.Width, image.Height)));
}
var button = new Button
{
Size = image.Size,
BackgroundImage = image,
BackgroundImageLayout = ImageLayout.Stretch,
Margin = new Padding(5),
Tag = cursor,
};
button.Click += onAnyClickCursorButton;
// Avoid confusion - see note.
button.MouseHover += (sender, e) => Cursor = Cursors.Default;
flowLayoutPanel.Controls.Add(button);
}
}
}
By attaching a Click event to each button, the current Cursor can be changed to the one clicked. To avoid visual confusion, if a different button is hovered over then return to the default cursor to more clearly indicate that the new style can now be clicked.
private void onAnyClickCursorButton(object? sender, EventArgs e)
{
if((sender is Button button) && (button.Tag is Cursor cursor))
{
Cursor = cursor;
}
}
}
Related
I made a video recorder that takes screenshots each frame and saves it in a temporary folder. When I press the Stop recording button it puts it all together in one video. I now need to have my program check the latest 2 screenshots it has taken and compare them to find changes, if change wasn't found the last image should get deleted. In the other hand if the 2 images had any difference, both images would stay there.
Thank you for helping me out!
Forms1.cs[Design]
Below is my Screen Recorder script
ScreenRecorder.cs
using System.IO;
using System.Drawing;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Accord.Video;
using Accord.Video.FFMPEG;
using GroupDocs.Comparison.Options;
using GroupDocs.Comparison;
namespace Timelapser_version_1._2
{
class ScreenRecorder
{
//Video variables:
private Rectangle bounds;
private string outputPath = "";
private string tempPath = "";
private int fileCount = 1;
private List<string> inputImageSequence = new List<string>();
//File variables:
private string audioName = "mic.wav";
private string videoName = "video.mp4";
private string finalName = "FinalVideo.mp4";
//Time variable:
Stopwatch watch = new Stopwatch();
//Audio variables:
public static class NativeMethods
{
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
public static extern int record(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
}
//ScreenRecorder Object:
public ScreenRecorder(Rectangle b, string outPath)
{
//Create temporary folder for screenshots:
CreateTempFolder("tempScreenCaps");
//Set variables:
bounds = b;
outputPath = outPath;
}
//Create temporary folder:
private void CreateTempFolder(string name)
{
//Check if a C or D drive exists:
if (Directory.Exists("D://"))
{
string pathName = $"D://{name}";
Directory.CreateDirectory(pathName);
tempPath = pathName;
}
else
{
string pathName = $"C://Documents//{name}";
Directory.CreateDirectory(pathName);
tempPath = pathName;
}
}
//Change final video name:
public void setVideoName(string name)
{
finalName = name;
}
//Delete all files and directory:
private void DeletePath(string targetDir)
{
string[] files = Directory.GetFiles(targetDir);
string[] dirs = Directory.GetDirectories(targetDir);
//Delete each file:
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
//Delete the path:
foreach (string dir in dirs)
{
DeletePath(dir);
}
Directory.Delete(targetDir, false);
}
//Delete all files except the one specified:
private void DeleteFilesExcept(string targetDir, string excDir)
{
string[] files = Directory.GetFiles(targetDir);
//Delete each file except specified:
foreach (string file in files)
{
if (file != excDir)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
}
}
//Clean up program on crash:
public void cleanUp()
{
if (Directory.Exists(tempPath))
{
DeletePath(tempPath);
}
}
//Return elapsed time:
public string getElapsed()
{
return string.Format("{0:D2}:{1:D2}:{2:D2}", watch.Elapsed.Hours, watch.Elapsed.Minutes, watch.Elapsed.Seconds);
}
//Record video:
public void RecordVideo()
{
//Keep track of time:
watch.Start();
int blac=0;
string a ="screenshot-1+%d";
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
//Add screen to bitmap:
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}
//Save screenshot:
string name = tempPath + "//screenshot-" + fileCount + ".png";
bitmap.Save(name, ImageFormat.Png);
inputImageSequence.Add(name);
fileCount++;
//Dispose of bitmap:
bitmap.Dispose();
}
}
//Record audio:
public void RecordAudio()
{
NativeMethods.record("open new Type waveaudio Alias recsound", "", 0, 0);
NativeMethods.record("record recsound", "", 0, 0);
}
//Save audio file:
private void SaveAudio()
{
string audioPath = "save recsound " + outputPath + "//" + audioName;
NativeMethods.record(audioPath, "", 0, 0);
NativeMethods.record("close recsound", "", 0, 0);
}
//Save video file:
public void SaveVideo(int width, int height, int frameRate)
{
using (VideoFileWriter vFWriter = new VideoFileWriter())
{
vFWriter.Open(outputPath + "//"+ videoName, width, height, frameRate, VideoCodec.MPEG4);
//Make each screenshot into a video frame:
foreach (string imageLocation in inputImageSequence)
{
Bitmap imageFrame = System.Drawing.Image.FromFile(imageLocation) as Bitmap;
vFWriter.WriteVideoFrame(imageFrame);
imageFrame.Dispose();
}
//Close:
vFWriter.Close();
}
}
//Combine video and audio files:
private void CombineVideoAndAudio(string video, string audio)
{
//FFMPEG command to combine video and audio:
string args = $"/c ffmpeg -i \"{video}\" -i \"{audio}\" -shortest {finalName}";
ProcessStartInfo startInfo = new ProcessStartInfo
{
CreateNoWindow = false,
FileName = "cmd.exe",
WorkingDirectory = outputPath,
Arguments = args
};
//Execute command:
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
public void Stop()
{
//Stop watch:
watch.Stop();
//Video variables:
int width = bounds.Width;
int height = bounds.Height;
int frameRate = 10;
//Save audio:
SaveAudio();
//Save video:
SaveVideo(width, height, frameRate);
//Combine audio and video files:
CombineVideoAndAudio(videoName, audioName);
//Delete the screenshots and temporary folder:
DeletePath(tempPath);
//Delete separated video and audio files:
DeleteFilesExcept(outputPath, outputPath + "\\" + finalName);
}
}
}
forms1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Timelapser_version_1._2
{
public partial class Timelapser : Form
{
string outputPath = "";
bool folderSelected = false;
string finalVidName = "FinalVideo.mp4";
// Screen recorder object:
ScreenRecorder screenRec = new ScreenRecorder(new Rectangle(), " ");
public Timelapser()
{
InitializeComponent();
}
private void Start_Click(object sender, EventArgs e)
{
bool containsMP4 = finalVidName.Contains(".mp4");
if (folderSelected && containsMP4)
{
screenRec.setVideoName(finalVidName);
timer1.Start();
}
else if(!folderSelected && containsMP4)
{
MessageBox.Show("You must select an output Folder before recording","Error");
}
else if (folderSelected && !containsMP4)
{
MessageBox.Show("You must select video name that ends in '.mp4'", "Error");
finalVidName = "FinalVideo.mp4";
}
}
private void Stop_Click(object sender, EventArgs e)
{
timer1.Stop();
screenRec.Stop();
Application.Restart();
}
private void timer1_Tick(object sender, EventArgs e)
{
screenRec.RecordVideo();
screenRec.RecordAudio();
Timelabel.Text = screenRec.getElapsed();
}
private void SelectFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
folderBrowser.Description = "Select an Output Folder";
if (folderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
outputPath = #folderBrowser.SelectedPath;
folderSelected = true;
Rectangle bounds = Screen.FromControl(this).Bounds;
screenRec = new ScreenRecorder(bounds,outputPath);
}
else
{
MessageBox.Show("Please select a folder");
}
}
I found the solution, to be able to check each 2 screenshots we need the function below.
public static List<bool> GetHash(Bitmap bmpSource)
{
List<bool> lResult = new List<bool>();
//create new image with 128x128 pixel
Bitmap bmpMin = new Bitmap(bmpSource, new System.Drawing.Size(128, 128));
for (int j = 0; j < bmpMin.Height; j++)
{
for (int i = 0; i < bmpMin.Width; i++)
{
//reduce colors to true / false
lResult.Add(bmpMin.GetPixel(i, j).GetBrightness() < 0.1f);
}
}
return lResult;
}
This function gets the screenshots and creates a 128x128 version of them. Also it changes the colour to black and white to get a true or false.
Then we need to call the function for each 2 screenshots as shown below.
List<bool> iHash1 = GetHash(new Bitmap(tempPath + "//screenshot-" + k + ".png"));
List<bool> iHash2 = GetHash(new Bitmap(tempPath + "//screenshot-" + (k + 1) + ".png"));
//determine the number of equal pixel (x of 256)
long equalElements = iHash1.Zip(iHash2, (i, j) => i == j).Count(eq => eq);
Debug.Write(equalElements);
if (equalElements > 16300 )
{
var filePath = tempPath + "//screenshot-" + (k+1) + ".png";
File.Delete(filePath);
}
i have a image. and i open it in image viewer that i created. now i want to edit this image. so i open this image in paint and when i click on save button after change it give me. some error of a sharing violation occurred while accessing.
i remove the file name from image viewer before open image in paint.
here is my code..
private void btnEditImage_Click(object sender, RoutedEventArgs e)
{
if (File.Exists(Helper.DefaultPath + listImages[count].Path))
{
SetNullImage();
string editPath = Helper.DefaultPath + listImages[count].Path;
if (File.Exists(editPath))
{
Process my = new Process();
my.StartInfo.FileName = "mspaint.exe";
my.StartInfo.Arguments = "\"" + editPath + "\"";
my.StartInfo.CreateNoWindow = true;
my.EnableRaisingEvents = true;
my.Exited += new EventHandler(myProcess_Exited);
my.Start();
}
}
}
private void myProcess_Exited(object sender, System.EventArgs e)
{
Dispatcher.Invoke(new Action(() =>
{
SetImage();
}));
}
See Images
Open In Image viewer:
thanks...
Error when make changes in image and click on save:
While you call SetImage() Method, make sure that you are using Image.FromFile() Method. If you using That, Use Bellow code instead of that
private Bitmap SetImage(){
pictureBox1.Image = GetImageFromPath(ImagePath)
}
private Bitmap GetImageFromPath(string Path)
{
using (StreamReader streamReader = new StreamReader(Path))
{
using (Bitmap tmpBitmap = (Bitmap)Bitmap.FromStream(streamReader.BaseStream))
{
return tmpBitmap;
}
}
}
My utility is supposed to resize either .jpg or .png files.
It seems to work fine in one location (at work, where I don't have IrfanView installed). But at home, when I open a *.jpg and then save it (resized), I see:
However, the image still displays fine in either case (whether I select "Yes" or "No" in the dialog.
IOW, I'm able to load and save both jpgs and pngs, and they save as such, and display fine. But IrfanView claims they are messed up.
Actually, I'm not sure how the image is saved; I was assuming it just saved it in the proper format "behind the scenes" based on the extension. Anyway, as this is a rather simple utility, I will just show all the code:
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace FileResizingUtil
{
public partial class FormFileResizer : Form
{
private Image _imgToResize;
String _originalFilename = String.Empty;
public FormFileResizer()
{
InitializeComponent();
}
private void buttonChooseImage_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog
{
InitialDirectory = "c:\\",
Filter = "JPG files (*.jpg)|*.jpg| PNG files (*.png)|*.png", FilterIndex = 2, RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
_originalFilename = ofd.FileName;
_imgToResize = Image.FromFile(_originalFilename);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
// If made it to here, it must be good
String preamble = labelImgSelected.Text;
labelImgSelected.Text = String.Format("{0}{1}", preamble, _originalFilename);
textBoxOrigHeight.Text = _imgToResize.Height.ToString();
textBoxOrigWidth.Text = _imgToResize.Width.ToString();
buttonApplyPercentageChange.Enabled = true;
//buttonResizeImage.Enabled = true;
}
private void buttonResizeImage_Click(object sender, EventArgs e)
{
// Really large images take awhile, so show an hourglass
Cursor.Current = Cursors.WaitCursor;
try
{
var size = new Size { Height = Convert.ToInt32(textBoxNewHeight.Text), Width = int.Parse(textBoxNewWidth.Text) };
// Two different ways of getting the int val
Image resizedImg = FileResizeUtils.GetResizedImage(_imgToResize, size);
String fileNameSansExtension = Path.GetFileNameWithoutExtension(_originalFilename);
String fileNameExtension = Path.GetExtension(_originalFilename);
String newFilename = String.Format("{0}{1}_{2}{3}", fileNameSansExtension, size.Height, size.Width, fileNameExtension);
// If used a different extension (jpg where the original was png, or vice versa) would the Save be intelligent enough to actually save in the other format?
resizedImg.Save(newFilename);
MessageBox.Show(String.Format("Done! File saved as {0}", newFilename));
Recycle();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
private void Recycle()
{
buttonResizeImage.Enabled = false;
buttonApplyPercentageChange.Enabled = false;
labelImgSelected.Text = "Image selected: ";
textBoxOrigHeight.Text = String.Empty;
textBoxOrigWidth.Text = String.Empty;
// Retain the percentage vals, as it may be that all in a batch need to be the same pair of vals
}
private void buttonApplyPercentageChange_Click(object sender, EventArgs e)
{
int origHeight = _imgToResize.Height;
int origWidth = _imgToResize.Width;
// Two ways to convert the val
double heightFactor = (double)numericUpDownHeight.Value / 100.0;
double widthFactor = Convert.ToDouble(numericUpDownWidth.Value) / 100.0;
if (heightFactor < 0 || widthFactor < 0)
{
// show an error - no negative values allowed- using updown, so that should not be possible
}
var newHeight = Convert.ToInt32(origHeight * heightFactor);
var newWidth = Convert.ToInt32(origWidth * widthFactor);
textBoxNewHeight.Text = newHeight.ToString();
textBoxNewWidth.Text = newWidth.ToString();
buttonResizeImage.Enabled = true;
}
private void textBoxNewHeight_TextChanged(object sender, EventArgs e)
{
EnableResizeButtonIfValidDimensionsEntered();
}
private void EnableResizeButtonIfValidDimensionsEntered()
{
if (String.IsNullOrWhiteSpace(textBoxOrigHeight.Text)) return;
String candidateHeight = textBoxNewHeight.Text;
String candidateWidth = textBoxNewWidth.Text;
int validHeight;
int validWidth;
buttonResizeImage.Enabled = (int.TryParse(candidateHeight, out validHeight)) &&
(int.TryParse(candidateWidth, out validWidth));
}
private void numericUpDownHeight_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownWidth.Value = numericUpDownHeight.Value;
}
}
private void numericUpDownWidth_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownHeight.Value = numericUpDownWidth.Value;
}
}
}
}
..and the GUI (just prior to hitting the "Resize Image" button:
UPDATE
Based on Eugene Sh.'ls comment, I changed my Save method to the following block:
bool success = true;
. . .
if (fileNameExtension != null && fileNameExtension.ToLower().Contains("jpg"))
{
resizedImg.Save(newFilename, ImageFormat.Jpeg);
}
else if (fileNameExtension != null &&
fileNameExtension.ToLower().Contains("png"))
{
resizedImg.Save(newFilename, ImageFormat.Png);
}
else
{
success = false;
}
if (success)
{
MessageBox.Show(String.Format("Done! File saved as {0}", newFilename));
}
else
{
MessageBox.Show("Something went awry. The file was not saved");
}
UPDATE 2
So here is my new code, implementing the suggestion, and supporting several new file types:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;
namespace FileResizingUtil
{
public partial class FormFileResizer : Form
{
private Image _imgToResize;
String _originalFilename = String.Empty;
public FormFileResizer()
{
InitializeComponent();
}
private void buttonChooseImage_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog
{
InitialDirectory = "c:\\",
Filter = "JPG files (*.jpg)|*.jpg| PNG files (*.png)|*.png| BMP files (*.bmp)|*.bmp| TIFF files (*.tiff)|*.png| ICO files (*.ico)|*.ico| EMF files (*.emf)|*.emf| WMF files (*.wmf)|*.wmf",
FilterIndex = 1, RestoreDirectory = true
};
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
_originalFilename = ofd.FileName;
_imgToResize = Image.FromFile(_originalFilename);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
if (String.IsNullOrWhiteSpace(_originalFilename)) return;
// If made it to here, it must be good
String preamble = labelImgSelected.Text;
labelImgSelected.Text = String.Format("{0}{1}", preamble, _originalFilename);
textBoxOrigHeight.Text = _imgToResize.Height.ToString();
textBoxOrigWidth.Text = _imgToResize.Width.ToString();
buttonApplyPercentageChange.Enabled = true;
}
private void buttonResizeImage_Click(object sender, EventArgs e)
{
bool success = true;
// Really large images take awhile, so show an hourglass
Cursor.Current = Cursors.WaitCursor;
try
{
// Two different ways of getting the int val
var size = new Size { Height = Convert.ToInt32(textBoxNewHeight.Text), Width = int.Parse(textBoxNewWidth.Text) };
Image resizedImg = FileResizeUtils.GetResizedImage(_imgToResize, size);
String fileNameSansExtension = Path.GetFileNameWithoutExtension(_originalFilename);
String fileNameExtension = Path.GetExtension(_originalFilename);
String newFilename = String.Format("{0}{1}_{2}{3}", fileNameSansExtension, size.Height, size.Width, fileNameExtension);
if (fileNameExtension != null && fileNameExtension.ToLower().Contains("jpg"))
{
resizedImg.Save(newFilename, ImageFormat.Jpeg);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("png"))
{
resizedImg.Save(newFilename, ImageFormat.Png);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("bmp"))
{
resizedImg.Save(newFilename, ImageFormat.Bmp);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("ico"))
{
resizedImg.Save(newFilename, ImageFormat.Icon);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("tiff"))
{
resizedImg.Save(newFilename, ImageFormat.Tiff);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("emf"))
{
resizedImg.Save(newFilename, ImageFormat.Emf);
}
else if (fileNameExtension != null && fileNameExtension.ToLower().Contains("wmf"))
{
resizedImg.Save(newFilename, ImageFormat.Wmf);
}
else
{
success = false;
}
MessageBox.Show(success
? String.Format("Done! File saved as {0}", newFilename)
: "Something went awry. The file was not saved");
Recycle();
}
finally
{
Cursor.Current = Cursors.Default;
}
}
private void Recycle()
{
buttonResizeImage.Enabled = false;
buttonApplyPercentageChange.Enabled = false;
labelImgSelected.Text = "Image selected: ";
textBoxOrigHeight.Text = String.Empty;
textBoxOrigWidth.Text = String.Empty;
// Retain the percentage vals, as it may be that all in a batch need to be the same pair of vals
}
private void buttonApplyPercentageChange_Click(object sender, EventArgs e)
{
int origHeight = _imgToResize.Height;
int origWidth = _imgToResize.Width;
// Two ways to convert the val
double heightFactor = (double)numericUpDownHeight.Value / 100.0;
double widthFactor = Convert.ToDouble(numericUpDownWidth.Value) / 100.0;
if (heightFactor < 0 || widthFactor < 0)
{
// show an error - no negative values allowed- using updown, so that should not be possible
}
var newHeight = Convert.ToInt32(origHeight * heightFactor);
var newWidth = Convert.ToInt32(origWidth * widthFactor);
textBoxNewHeight.Text = newHeight.ToString();
textBoxNewWidth.Text = newWidth.ToString();
buttonResizeImage.Enabled = true;
}
private void textBoxNewHeight_TextChanged(object sender, EventArgs e)
{
EnableResizeButtonIfValidDimensionsEntered();
}
private void EnableResizeButtonIfValidDimensionsEntered()
{
if (String.IsNullOrWhiteSpace(textBoxOrigHeight.Text)) return;
String candidateHeight = textBoxNewHeight.Text;
String candidateWidth = textBoxNewWidth.Text;
int validHeight;
int validWidth;
buttonResizeImage.Enabled = (int.TryParse(candidateHeight, out validHeight)) &&
(int.TryParse(candidateWidth, out validWidth));
}
private void numericUpDownHeight_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownWidth.Value = numericUpDownHeight.Value;
}
}
private void numericUpDownWidth_ValueChanged(object sender, EventArgs e)
{
if (checkBoxRetainRatio.Checked)
{
numericUpDownHeight.Value = numericUpDownWidth.Value;
}
}
}
}
From the Image.Save documentation:
If no encoder exists for the file format of the image, the Portable
Network Graphics (PNG) encoder is used. When you use the Save method
to save a graphic image as a Windows Metafile Format (WMF) or Enhanced
Metafile Format (EMF) file, the resulting file is saved as a Portable
Network Graphics (PNG) file. This behavior occurs because the GDI+
component of the .NET Framework does not have an encoder that you can
use to save files as .wmf or .emf files.
If you want to save in a different format, use the overloaded Save method, taking format as a second parameter:
Save(String, ImageFormat)
Most image viewers don't use the extension of the file to determine the type of the file, but use so called "magic numbers" (http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files). They basically check the first X bytes of the file wich is often unique to a specific image format.
My guess is, that the library you're using saves the file as PNG as default (edit: see Eugenes answer), not considering what extension you put there. IrfanView notices, that the magic number and the extension don't match but still shows the image by defaulting to the magic number.
Go to a console and print out the file. If it is a PNG file, you will see PNG displayed and it stops.
If is is JPEG, you will get a lot of garbage but should see EXIF or JFIF at the top. The very start is FF D8
Because the JPEG and PNG have different signatures, the application can tell them apart from their contents and invite the appropriate decoder.
Image applications normally identify the type of image from the contents of the stream, not the extension.
Problem: I don't want the user to decide which location the recorded WAV file should be saved,the wav file should save in c:\ . for example when button 2 is clicked the wav file saves to "c:\". I hope you guys can help me.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
//voice recorder
namespace recorder
{
public partial class Form1 : Form
{
[DllImport("winmm.dll")]
private static extern int mciSendString(string MciComando, string MciRetorno, int MciRetornoLeng, int CallBack);
string musica = "";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
label1.Visible = false; //label1.Text=recording
}
//starts recording what I say to mic
private void btnStart_Click(object sender, EventArgs e)
{
label1.Visible = true;
mciSendString("open new type waveaudio alias Som", null, 0, 0);
mciSendString("record Som", null, 0, 0);
}
//stops recording and shows a save form
//This is where the problem is.
/* I don't want the program to ask the user for location and file name and format to be
saved as. I just want the file to save in c:\ with the filename "recording1" with format
as .wav */
private void btnStopnSave_Click(object sender, EventArgs e)
{
label1.Visible = false;
mciSendString("pause Som", null, 0, 0);
SaveFileDialog save = new SaveFileDialog();
save.Filter = "WAVE|*.wav";
if (save.ShowDialog() == DialogResult.OK) // this is where it needs to be altered
{
mciSendString("save Som " + save.FileName,null,0, 0);
mciSendString("close Som", null, 0, 0);
}
}
//lets user to open a WAV file by browsing files
private void btnPlay_Click(object sender, EventArgs e)
{
if (musica == "")
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Wave|*.wav";
if (open.ShowDialog() == DialogResult.OK) { musica = open.FileName; }
}
mciSendString("play " + musica, null, 0, 0);
}
}
}
Just don't show the Dialog and put a constant string instead of using the instance of class SaveFileDialog.
var fileName = "C:/mySound.wav";
mciSendString("save Som " + fileName,null,0, 0);
mciSendString("close Som", null, 0, 0);
Try this:
private void StopRecordingAndSave(string OutputFolerPath, string OutputFileName)
{
mciSendString(#"save recsound" + OutputFolderPath + OutputFileName + ".wav","",0,0);
mciSendString(#"close recsound ","", 0,0);
}
I am totally new to C# coding - I am trying to take screen shots of webpages whose URLs are initially picked up form a notepad uploaded on the same form.
As I read through the documentation on the web_browser control in MSDN.. I did arrive at the following code - yet when I run, I only get white screens
I tried uploading a .txt with (google/yahoo URLs as test data in 2 lines)
Can someone please say what more should I take care apart from handling which should get what I want as I read in MSDN.
P.S: pls forgive if I'm terribly wrong in coding style .. as aforesaid I'm just starting my C# coding :)
Code that I tried...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MSDN_wbc_tut1
{
public partial class Form1 : Form
{
public int temp = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void FileUploadButton1_Click(object sender, EventArgs e)
{
//once a file is uploaded i want Pgm to read contents & browse them as URLS
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.CheckFileExists = true;
openFileDialog.AddExtension = true;
openFileDialog.Multiselect = true;
//Filtering for Text files alone
openFileDialog.Filter = "text files (*.txt)|*.txt";
//if file is selected we must then do our coding part to proceed hecneforth
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//my code to say pgm wat to do once upload done...
//Getting my Chosen file's name
string Fileuploaded = openFileDialog.FileName;
//Read all line opens files - reads till EOF & closes ,prevents a while condition
string[] FileuploadedContent = System.IO.File.ReadAllLines(Fileuploaded);
foreach (string s in FileuploadedContent)
{
NavigateContent(s);
}
}
}
private void NavigateContent(string lineasurl)
{
// Add an event handler that images the document after it loads.
try
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler
(takescreen);
webBrowser1.Navigate(new Uri(lineasurl));
//webBrowser1.Navigate(lineasurl); also works
}
catch (System.UriFormatException)
{
return;
}
}
private void takescreen(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//specifying sample values for image or screenshot size
int x = 600, y = 700;
Bitmap bitmap = new Bitmap(x, y);
webBrowser1.DrawToBitmap(bitmap, new Rectangle(0, 0, x, y));
//to give each screen a unique name - i append some no onto it
temp = temp + 1;
string TempFname = "Screenshotref" + temp.ToString() + "." + "jpg";
bitmap.Save(TempFname);
}
}
}