繁体   English   中英

将 bitmap 保存在与原始名称相同的文件夹中

[英]Save a bitmap at same folder as the original with a set name

我想制作一个程序,通过在控制台中输入加载文件,将图片转换为灰度、负片和模糊。 然后我想在与原始文件相同的文件夹中复制转换后的图片,并在文件名中添加额外的文本(例如:picture_negative.jpg)。 我的问题是我无法弄清楚如何将图片与额外的文本一起保存在保存文件夹中。

这是我编程的第一个月,所以我不是很有经验。

static void Main(string[] args)
        {
            Bitmap picture;
            try
            {
                Console.Write("Write the file you want to edit ");
                picture = new Bitmap(Console.ReadLine=                 
            }
            catch (ArgumentNullException)
            {
                Console.WriteLine("No picture choosen");
                return;
            }
            catch (ArgumentException)
            {
                Console.WriteLine("error");
                return;
            }

            ConvertAlgoritms.ConvertAlgoritms.MakePictureGreyScale(picture);
            ConvertAlgoritms.ConvertAlgoritms.MakePictureNegative(picture);
            ConvertAlgoritms.ConvertAlgoritms.MakePictureBlurred(picture);
        }

class 示例

 public class ConvertAlgoritms
    {
        public static Bitmap MakePictureGreyScale(Bitmap originalPicture)
        {
            Bitmap newPicture = new Bitmap(originalPicture);

            int x, y;
            for (x = 0; x < newPicture.Width; x++)
            {
                for (y = 0; y < newPicture.Height; y++)
                {
                    Color pixel = newPicture.GetPixel(x, y);
                    int r = pixel.R;
                    int g = pixel.G;
                    int b = pixel.B;
                    int greyScale = (r + g + b) / 3;
                    newPicture.SetPixel(x, y, Color.FromArgb(greyScale, greyScale, greyScale));
                }
            }
            return newPicture;
        }
}

你有Bitmap.Save()

首先,您必须将控制台中输入的文件名保存到变量中。

然后,你可以在 append 一个字符串到这个名字前扩展。

例子:

Console.Write("Write the file you want to edit ");
Filename = Console.ReadLine();
picture = new Bitmap(Filename);

string NewFilename = Path.GetFileNameWithoutExtension(Filename)
                   + StrToAppend
                   + Path.GetExtension(Filename);

picture.Save(Newfilename, picture.RawFormat);

您需要拿起返回的图像,例如:

var greyscalePicture = ConvertAlgoritms.ConvertAlgoritms.MakePictureGreyScale(picture);

然后你可以保存它:

greyscalePicture.Save("Fancynewfilename.jpg", ImageFormat.Jpeg);

这假定您的文件格式是 JPEG。 要生成新文件名,您需要保留对旧文件名的引用。

var originalFilename = Console.ReadLine();
var picture = new Bitmap(originalFilename);

然后,您可以按照@Corak 的建议使用Path class 构建文件名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM