谢谢浏览。
最近整理一下该代码的所实现的功能,以下源码可以直接copy使用,如果程序碰到啥问题欢迎评论区共同探讨。
这里是可以直接运行的程序和代码:
链接:https://pan.baidu.com/s/1zJ8k-wZGKNwhXCX3Wj8phw
提取码:c8e7
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Text;
using static System.Net.Mime.MediaTypeNames;
namespace 图片大小转换
{
class Program
{
static int width = 0;
static int height = 0;
static void Main(string[] args)
{
Console.WriteLine("请输入图片的地址和图片名:例如 E:/a.jpg");
string path = Console.ReadLine();
Console.WriteLine("请输入所需图片的宽高:例如200-300,以‘-’分割");
string picLength = Console.ReadLine();
if (picLength.Contains("-"))
{
try
{
width = int.Parse(picLength.Split('-')[0]);
height = int.Parse(picLength.Split('-')[1]);
}
catch (Exception ex)
{
Console.WriteLine("这可不像是宽高值!");
width = height = 200;
}
}
if (string.IsNullOrWhiteSpace(path) || !path.Contains("."))
{
Console.WriteLine("图片地址不能为空或者不能没有目标图片");
}
else
{
try
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); //将图片以文件流的形式进行保存
BinaryReader br = new BinaryReader(fs);
byte[] buffer = br.ReadBytes((int)fs.Length); //将流读入到字节数组中
//Byte转为Image对象
MemoryStream ms = new MemoryStream(buffer);
System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
//设置画布,绘画新图片
Bitmap b = new Bitmap(width, height);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//绘制图像
g.DrawImage(image, 0, 0, width, height);
g.Dispose();
//保存图片
b.Save(path.Substring(0, path.LastIndexOf('.')) + "副本." + path.Substring(path.LastIndexOf('.')));
Console.WriteLine("转换完成,请源文件路劲下查看!");
}
catch (Exception ex)
{
Console.WriteLine("学习使用,请勿乱搞!");
}
}
Console.ReadKey();
}
}
}
转换的效果对比
历史分割线,以下代码可以参考;
以下代码参考自:https://www.cnblogs.com/fjzhang/p/10677702.html,多谢前辈领路。
byte[] buffer = new byte[1];
//Byte转为Image对象
MemoryStream ms = new MemoryStream(buffer);
Image image = System.Drawing.Image.FromStream(ms);
//设置画布,绘画新图片
Bitmap b = new Bitmap(200, 200);
Graphics g = Graphics.FromImage((System.Drawing.Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
//绘制图像
g.DrawImage(image, 0, 0, 200, 200);
g.Dispose();
//保存图片
b.Save("aaaaaaaaa");