Reputation: 11
Faced such a problem "System.ArgumentException", while writing an envelope from an image (.jpg) in a text file with a picture (ASCII). Did according to the instructions (https://www.bilibili.com/video/av5862027/)
For the second or third day I try to solve this problem.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;
namespace ayy
{
class Program
{
static void Main(string[] args)
{
FileStream stream = new FileStream(@"meme.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(stream);
for (int imageNumber = 0; imageNumber <= 7600; imageNumber++)
{
string url = @"C:\Users\Admin\source\repos\badapple\ayy\ba\ba";
if (imageNumber < 10)
{
url += "00000";
}
else if (imageNumber < 100)
{
url += "0000";
}
else if (imageNumber < 1000)
{
url += "000";
}
else
{
url += "00";
}
url += imageNumber.ToString() + ".jpg";
Bitmap image = new Bitmap(url, true);
for (int y = 0; y < image.Height; y++)
{
string str = "";
for (int x = 0; x < image.Width; x++)
{
Color pixel = image.GetPixel(x, y);
if (pixel.R > 200)
{
str += "#";
}
else
{
str += " ";
}
writer.WriteLine(str);
}
Console.WriteLine(url);
}
writer.Close();
}
}
}
}
Upvotes: 0
Views: 934
Reputation: 81473
using
, using
, using
Every time you go to play with something (or create an object) check if you can use a using
statement
If you expect a file to be there, do some due diligence and check if it exists
If you want to join paths and file names, use Path.Combine()
GetPixel
is extremely slow, so probably better to use LockBits
Why use lots of if
s to add 0
's when you can use a format specifier $"{imageNumber:D5}.jpg"
Truthfully, i am not sure if this will fix your problem, but you are much better place regardless
using (var stream = new FileStream(@"meme.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
using (var writer = new StreamWriter(stream))
{
for (var imageNumber = 0; imageNumber <= 7600; imageNumber++)
{
var dir = @"C:\Users\Admin\source\repos\badapple\ayy\ba\ba";
var fileName = Path.Combine(dir, $"{imageNumber:D5}.jpg");
if (File.Exists(fileName))
{
throw new FileNotFoundException($"Woah, what now : {fileName}");
}
using (var image = new Bitmap(fileName, true))
{
for (var y = 0; y < image.Height; y++)
{
for (var x = 0; x < image.Width; x++)
{
var pixel = image.GetPixel(x, y);
writer.Write(pixel.R > 200 ? "#" : " ");
}
writer.WriteLine();
}
}
}
}
}
If you are still having problems, work out what file is causing the problem, check to see if it is actually an image and loads. My spidey senses tells me its not
Upvotes: 1