C# Bitmap: System.ArgumentException "Invalid parameter." - c#

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();
}
}
}
}

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 ifs 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

Related

Generated .txt file doesn't show up

So, I'm tryng to generating a txt file with a matrix of 0 and 1, where all the borders are 0 and the body of the matrix is randomly filled with both values. It should be a bitMap where 0 is an obstacle and 1 is a possibile node for pathfinding algorythm. The Method should be called multiple times to generate and save in the folder as mush maps as the user want.
I made this class to generate the map:
public static class GenerateText
{
static string obstacle = "0";
static string node = "1";
public static void CreateMap(int x, int y, string name)
{
string path = "Assets/" + name + ".txt";
if(!File.Exists(name + ".txt"))
{
FileStream fs = File.Create(path);
StreamWriter writer = new StreamWriter(fs);
string[,] map = new string[x, y];
for (int i = 0; i < x; ++i)
{
for (int h = 0; h < y; ++h)
{
int randomValue = RandomGenerator.GetRandom(0, 10);
if (randomValue > 6 || i == 0 || h == 0 || i == x || h == y)
{
map[i, h] = obstacle;
}
else
{
map[i, h] = node;
}
}
}
fs.Close();
writer.WriteLine(map);
}
}
}
and the result should be something like this:
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,1,1,1,1,1,1,1,1,1,1,1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,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
The called method works fine and reach the end, but if i check the solution the file that was supposed to be generated is missing.
I'm new to this kind of things so it's probably a dumb question, but can someone help me?
1- You are closing filestream before you write anything
2- You are trying to write a array . But you send just array object to the file you need the loop for that
public static class GenerateText
{
static string obstacle = "0";
static string node = "1";
public static void CreateMap(int x, int y, string name)
{
string path = Directory.GetCurrentDirectory() + "/" + name + ".txt";
if (!File.Exists(name + ".txt"))//if there is a empty file with this name
{ //function doesnt work make sure you
//delete any empty file
FileStream fs = File.Create(path);
StreamWriter writer = new StreamWriter(fs);
string[,] map = new string[x, y];
for (int i = 0; i < x; ++i)
{
for (int h = 0; h < y; ++h)
{
int randomValue = RandomGenerator.GetRandom(0, 10);
if (randomValue > 6 || i == 0 || h == 0 || i == x || h == y)
{
map[i, h] = obstacle;
}
else
{
map[i, h] = node;
}
}
}
for (int a = 0; a < x; a++)
{
for (int b = 0; b < y; b++)
{
writer.Write(map[a, b]);
}
writer.WriteLine();
}
writer.Close();
fs.Close();
}
}
}
You are closing your filestream before you write to your StreamWriter!
fs.Close();
writer.WriteLine(map);
It is better to have Using statements for such cases, then you minimise such problems. With or without brackets is your choice.
using (FileStream fs = File.Create(path))
using (StreamWriter writer = new StreamWriter(fs))
string[,] map = new string[x, y];
for (int i = 0; i < x; ++i)
{
for (int h = 0; h < y; ++h)
{
int randomValue = RandomGenerator.GetRandom(0, 10);
if (randomValue > 6 || i == 0 || h == 0 || i == x || h == y)
{
map[i, h] = obstacle;
}
else
{
map[i, h] = node;
}
}
}
writer.WriteLine(map);

How to extract quantization matrices from a JPEG in C#

Is it possible to extract the quantization matrices of a JPG file in C#? I have found the libjpeg.NET but I cannot figure out how to retrieve the QTs matrices. Please find below my code.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BitMiracle.LibJpeg;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
string file = #"PATH_TO_FILE";
JpegImage img = new JpegImage(file);
Console.Read();
// Ideally, there should be some img.GetQuantizationMatrix() method
}
}
}
If you just want the quantization tables (and nothing else), it is a simple matter to scan the JPEG stream for the DQT marker (FFDB-followed by a 2-byte length) and extract the values.
You do not need to decode the image to get this information.
Thanks to the suggestion by #user3344003, I managed to read the JPEG header to extract quantization matrix information. I followed the file layout spec presented in this web page.
void Main()
{
string folder = #"PATH_TO_FILE";
var files = Directory.GetFiles(folder, "*jpg", SearchOption.AllDirectories);
byte dqt = 0xDB;
foreach (string file in files)
{
file.Dump();
byte[] s = File.ReadAllBytes(file);
for (int i = 0; i < s.Length-1; i++) {
byte b1 = s[i];
byte b2 = s[i+1];
if (b1 == 0xff && b2 == 0xdb) {
int field_length = s[i + 2] + s[i + 3];
int matrix_length = field_length - 3;
int qt_info = s[i + 4];
("QT info" + qt_info).Dump();
("QT Matrix").Dump();
byte[] mat = new byte[matrix_length];
for (int k = 0; k < matrix_length; k++) {
mat[k] = s[i+5+k];
}
Print8x8Matrix(mat);
}
}
}
}
public static void Print8x8Matrix(byte[] bytes)
{
string s = "";
for (int i= 0; i < bytes.Length; i++) {
s += bytes[i] + " ";
if (i % 8 == 0)
{
s.Dump();
s="";
}
}
}

OutOfMemory while adding pictures to Excel Sheet

I have problem with memory.
I want do add pictures to my excel. Picuters are on azure blob.
After 1k of added pictures my program slowing so much till outofmemory exception.
I will paste my code here:
string filePath = #"excel.xlsx";
int i = 0;
public void Generate(int worksheetnumber)
{
using (FileStream fileStream = File.Open(filePath, FileMode.Open))
{
var package = new ExcelPackage(fileStream);
ExcelWorksheet workSheet = package.Workbook.Worksheets[worksheetnumber];
workSheet.Column(2).Width = 21;
workSheet.Column(4).Width = 21;
for (int j = workSheet.Dimension.Start.Row + 1; j <= workSheet.Dimension.End.Row; j++)
{
InsertImage(workSheet, j, 1);
InsertImage(workSheet, j, 3);
}
string path = string.Format(#"{0}.xlsx", worksheetnumber);
Stream stream2 = File.Create(path);
package.SaveAs(stream2);
stream2.Close();
}
}
private void InsertImage(ExcelWorksheet workSheet, int j, int columnNumber)
{
if (!string.IsNullOrEmpty(workSheet.Cells[j, columnNumber].Text))
{
try
{
var splittedUrlHash = workSheet.Cells[j, columnNumber].Text.Split('/');
using (var stream = DownloadBlobFileToStream(splittedUrlHash[1], splittedUrlHash[0], SHOP))
{
Image image = Image.FromStream(stream);
var picture = workSheet.Drawings.AddPicture(string.Format("{0}{1}", j, columnNumber+1), image);
stream.Close();
picture.From.Column = columnNumber;
picture.From.Row = j - 1;
picture.To.Column = columnNumber;
picture.To.Row = j - 1;
picture.SetSize(150, 120);
workSheet.Row(j).Height = 100;
Debug.WriteLine("Dodano obrazek - {0}", i);
i++;
}
}
catch (System.ArgumentException e)
{
}
}
}
I want to admit, I have a link images in Columns 1 and 3. Images are locating in cols 2 and 4.
Is there any solution to handle this error in this case without losing images, or leaving empty cells

NPOI AutoSizeColumn not resizing correctly

I've put the .AutoSizeColumn right before the write Method
int numberOfColumns = sheet.GetRow(rowcount - 1).PhysicalNumberOfCells;
for (int i = 0; i <= numberOfColumns; i++)
{
sheet.AutoSizeColumn(i);
GC.Collect();
}
using (var fileData = new FileStream(#"C:\Temp\Contatti.xlsx", FileMode.Create))
{
wb.Write(fileData);
}
this is an example of the result
The problem also migh be, that PhysicalNumberOfCells can return 1, even if you have a cell lets say in 'Z' column. There is LastCellNum property,you i instead of PhysicalNumberOfCells:
int lastColumNum = sheet.GetRow(0).LastCellNum;
for (int i = 0; i <= lastColumNum; i++)
{
sheet.AutoSizeColumn(i);
GC.Collect();
}
using (var fileData = new FileStream(#"D:\Contatti.xlsx", FileMode.Create))
{
wb.Write(fileData);
}

File Byte Array Encryption corrupt the file except Text Document

I made a simple file binary encrypt/decrypt and it works perfectly for any text document.
But when I encrypt and decrypt image / word document file, the file corrupt.
I don't understand why this happen.
This is my code to get the file byte array.
byte[] b = null;
using (System.IO.FileStream fr = new System.IO.FileStream(this.txtFile.Text, System.IO.FileMode.Open))
{
using (System.IO.BinaryReader br = new System.IO.BinaryReader(fr))
{
b = br.ReadBytes((int)fr.Length);
}
}
And this is how I write all the bytes back.
System.IO.File.WriteAllBytes(filepath, b);
Can someone explain to me why?
Edit : This is my Encrypt/Decrypt code.
Sorry if its messy, I'm new to cryptograph.
for (int i = 0; i < b.Length; i++)
{
if (keyIndex >= key.Length)
{
keyIndex = 0;
}
string fileBIN = Convert.ToString(b[i], 2);
string keyBIN = Convert.ToString(Convert.ToInt32(Convert.ToChar(key[keyIndex])), 2);
string newBIN = string.Empty;
keyIndex += 1;
if (fileBIN.Length > keyBIN.Length)
{
for (int x = 0; x < Math.Abs(fileBIN.Length - keyBIN.Length); x++) { keyBIN = "0" + keyBIN; x -= 1; }
}
else
{
for (int x = 0; x < Math.Abs(fileBIN.Length - keyBIN.Length); x++) { fileBIN = "0" + fileBIN; x -= 1; }
}
if (fileBIN == keyBIN)
{
newBIN = fileBIN;
}
else
{
for (int x = 0; x < fileBIN.Length; x++)
{
if (fileBIN.Substring(x, 1).ToString() == keyBIN.Substring(x, 1).ToString()) { newBIN += "0"; }
else { newBIN += "1"; }
}
}
b[i] = Convert.ToByte(newBIN, 2);
}

Categories

Resources