using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Threading; namespace ConfigLab.Comp.Img.ImgUtils
{
/// <summary>
/// 功能简介:图片转换类
/// 创建时间:2016-9-10
/// 创建人:pcw
/// 博客:http://www.cnblogs.com/taohuadaozhu
/// </summary>
public class ImgConvert
{
/// <summary>
/// 字节数组转换为bitmap
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static Bitmap BytesToBitmap(byte[] buffer)
{
Bitmap bitmapResult = null;
if (buffer != null && buffer.Length > 0)
{
using (MemoryStream ms = new MemoryStream(buffer))
{
try
{
bitmapResult = new Bitmap(ms);
return bitmapResult;
}
catch (Exception error)
{
return bitmapResult;
}
finally
{
ms.Close();
ms.Dispose();
}
}
}
return null;
}
/// <summary>
/// 字节数组转换为Image对象
/// </summary>
/// <param name="buffer"></param>
/// <returns></returns>
public static Image BytesToImage(byte[] buffer)
{
if (buffer != null && buffer.Length > 0)
{
using (MemoryStream ms = new MemoryStream(buffer))
{
Image image = null;
try
{
image = Image.FromStream(ms);
return image;
}
catch (Exception error)
{
return image;
}
finally
{
ms.Close();
ms.Dispose();
}
}
}
return null; } /// <summary>
/// 按照一定的比率进行放大或缩小
/// </summary>
/// <param name="Percent">缩略图的宽度百分比 如:需要百分之80,就填0.8</param>
/// <param name="rotateFlipType">
///顺时针旋转90度 RotateFlipType.Rotate90FlipNone
///逆时针旋转90度 RotateFlipType.Rotate270FlipNone
///水平翻转 RotateFlipType.Rotate180FlipY
///垂直翻转 RotateFlipType.Rotate180FlipX
///保持原样 RotateFlipType.RotateNoneFlipNone
/// </param>
/// <param name="IsTransparent">背景是否透明</param>
/// <returns>Bitmap对象</returns>
public static Bitmap GetImage_Graphics(Image ResourceImage, double Percent, RotateFlipType rotateFlipType, bool IsTransparent)
{
Bitmap ResultBmp = null;
try
{
if (ResourceImage != null)
{
ResourceImage.RotateFlip(rotateFlipType);
int _newWidth = (int)Math.Round(ResourceImage.Width * Percent);
int _newHeight = (int)Math.Round(ResourceImage.Height * Percent);
ResultBmp = new System.Drawing.Bitmap(_newWidth, _newHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);//创建图片对象
Graphics g = null;
try
{
g = Graphics.FromImage(ResultBmp);//创建画板并加载空白图像
if (g != null)
{
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; //System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;//设置保真模式为高度保真
g.DrawImage(ResourceImage, new Rectangle(0, 0, _newWidth, _newHeight), 0, 0, ResourceImage.Width, ResourceImage.Height, GraphicsUnit.Pixel);//开始画图
if (IsTransparent)
{
ResultBmp.MakeTransparent(System.Drawing.Color.Transparent);
}
}
}
catch (Exception errr)
{
ConfigLab.Utils.SaveErrorLog(string.Format("GetImage_Graphics(1),异常={0}", errr.Message));
Thread.Sleep(100);
}
finally
{
if (g != null)
{
g.Dispose();
}
}
}
}
catch (Exception ex)
{
ConfigLab.Utils.SaveErrorLog(string.Format("GetImage_Graphics(2),异常={0}", ex.Message));
Thread.Sleep(100);
return null;
}
finally
{
if (ResourceImage != null)
{
ResourceImage.Dispose();
}
}
return ResultBmp;
}
/// <summary>
/// 图片等比缩放
/// </summary>
/// <param name="sImgFilePath"></param>
/// <param name="Percent"></param>
/// <returns></returns>
public static bool ChangeImgSize(string sImgFilePath, double Percent,string sNewImgFilePath)
{
Image img = null;
Bitmap bp = null;
bool bSuccess = false;
try
{
if (File.Exists(sImgFilePath) == false)
{
Utils.SaveErrorLog(string.Format("找不到待压缩的原文件{0}", sImgFilePath));
return false;
}
img = Image.FromFile(sImgFilePath);
if (img != null)
{
bp = GetImage_Graphics(img, Percent, RotateFlipType.RotateNoneFlipNone, true);
if (bp != null)
{
string sDirectory = FilePathUtils.getDirectory(sNewImgFilePath);
if (sDirectory.EndsWith("\\") == false)
{
sDirectory = string.Format("{0}\\", sDirectory);
}
bp.Save(sNewImgFilePath);
bSuccess=true;
}
}
}
catch(Exception ex)
{
Utils.SaveErrorLog(string.Format("ChangeImgSize处理{0}的图片且保存到{1}的任务执行失败",sImgFilePath,sNewImgFilePath), ex);
}
finally
{
if (img != null)
{
img.Dispose();
}
if (bp != null)
{
bp.Dispose();
}
}
return bSuccess;
}
/// <summary>
/// Resize图片
/// </summary>
/// <param name="bmp">原始Bitmap</param>
/// <param name="newW">新的宽度</param>
/// <param name="newH">新的高度</param>
/// <returns>处理以后的Bitmap</returns>
public static Bitmap ResizeBmp(Bitmap bmp, int newW, int newH)
{
try
{
Bitmap b = new Bitmap(newW, newH);
Graphics g = Graphics.FromImage(b);
g.SmoothingMode = SmoothingMode.HighSpeed;
g.CompositingQuality = CompositingQuality.HighSpeed;
g.InterpolationMode = InterpolationMode.Low;
g.DrawImage(bmp, new Rectangle(0, 0, newW, newH), new Rectangle(0, 0, bmp.Width, bmp.Height), GraphicsUnit.Pixel);
g.Dispose(); return b;
}
catch
{
return null;
}
} /// 将图片Image转换成Byte[]
/// </summary>
/// <param name="Image">image对象</param>
/// <param name="imageFormat">后缀名</param>
/// <returns></returns>
public static byte[] ImageToBytes(Image Image, System.Drawing.Imaging.ImageFormat imageFormat)
{
if (Image == null) { return null; }
byte[] data = null;
using (MemoryStream ms = new MemoryStream())
{
using (Bitmap Bitmap = new Bitmap(Image))
{
Bitmap.Save(ms, imageFormat);
ms.Position = 0;
data = new byte[ms.Length];
ms.Read(data, 0, Convert.ToInt32(ms.Length));
ms.Flush();
}
}
return data;
} /// <summary>
/// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static Bitmap ReadImageFile(string path)
{
if (string.IsNullOrEmpty(path))
return null;
if (File.Exists(path) == false)
return null;
int filelength = 0;
Bitmap bit = null;
Byte[] image = null;
try
{
using (FileStream fs = File.OpenRead(path))//OpenRead
{
filelength = (int)fs.Length; //获得文件长度
image = new Byte[filelength]; //建立一个字节数组
fs.Read(image, 0, filelength); //按字节流读取
System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
bit = new Bitmap(result);
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
}
catch (Exception err)
{
ConfigLab.Utils.SaveErrorLog(string.Format("读取图片【{0}】失败,调试信息={1}", path, err.Message + err.StackTrace));
}
finally
{
if (image != null)
{
image = null;
}
}
return bit;
}
}
}

分享一个项目中在用的图片处理工具类(图片缩放,旋转,画布格式,字节,image,bitmap转换等)的更多相关文章

  1. Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!

    Go/Python/Erlang编程语言对比分析及示例   本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...

  2. eclipse中将一个项目作为library导入另一个项目中

    1. github上搜索viewpagerIndicator: https://github.com/JakeWharton/ViewPagerIndicator2. 下载zip包,解压,eclips ...

  3. 解决tomcat下面部署多个项目log4j的日志输出会集中输出到一个项目中的问题

    在一次项目上线后,发现了一个奇怪的问题,经过对源码的阅读调试终于解决,具体经过是这样的: 问题描述:tomcat7下面部署多个项目,log4j的日志输出会集中输出到一个项目中,就算配置了日志文件的绝对 ...

  4. (转)最近一个项目中关于NGUI部分的总结(深度和drawCall)

    在自己最近的一个项目中,软件的界面部分使用了NGUI来进行制作.在制作过程中,遇到了一些问题,也获取了一些经验,总结下来,作为日后的积累. 1.NGUI图集的使用. 此次是第一个自己正儿八经的制作完整 ...

  5. 当一个项目中同时存在webroot和webcontext时

    当一个项目中同时存在webroot和webcontext时,注意一定要删除那些没在使用的.还有要发布其中一个想要的目录到服务器中,具体方法是  选择相应工程-----properties-----de ...

  6. VS编译linux项目生成静态库并在另一个项目中静态链接的方法

    VS2017也推出很久了,在单位的时候写linux的服务端程序只能用vim,这让用惯了IDE的我很难受. 加上想自己撸一套linux上的轮子,决定用VS开工远程编写调试linux程序. 在window ...

  7. vs2010 C# 如何将类做成DLL 再从另一个项目中使用这个类

    vs2010 C# 如何将类做成DLL 再从另一个项目中使用这个类 2011-10-20 12:00 486人阅读 评论(0) 收藏 举报 一.将类做成DLL 方法一: 你可以通过在命令行下用命令将以 ...

  8. 一个项目中:只能存在一个 WebMvcConfigurationSupport (静态文件失效之坑)

    一个项目中:只能存在一个 WebMvcConfigurationSupport 在一个项目中WebMvcConfigurationSupport只能存在一个,多个的时候,只有一个会生效. 静态文件访问 ...

  9. 解决:一个项目中写多个包含main函数的源文件并分别调试运行

    自己在学c++的时候,一个项目中的多个cpp文件默认不允许多个main函数的出现,但是通过选项操作能够指定单个cpp文件进行运行,如下: 1.此时我就想运行第二个cpp文件,我们只需要把其他的两个右键 ...

  10. 分享一个非常好用又好看的终端工具--Hyper (支持windows、MacOS、Linux)

    分享一个非常好用又好看的终端工具--Hyper 官网地址: https://hyper.is/ 打开官网,选择对应版本安装即可:(可能网络原因,无法下载, 可以从我分享的链接下载 链接: https: ...

随机推荐

  1. POJ1185 [NOI2001] 炮兵阵地 (状压DP)

    又是一道有合法性检测的状压题. dp[i][j][k]表示第i行状态为j,i-1行状态为k时前i行放置的最大数量. 注意22行统计二进制数中1的个数时的巧妙方法. 1 #include<cstd ...

  2. Mysql编程中遇到的小错误

    我在mysql中创建的数据库表语句为如下 create table grade (id int not null, name varchar(255), desc varchar(255), prim ...

  3. day01-4-订座功能

    满汉楼01-4 4.功能实现03 4.5订座功能 4.5.1功能说明 如果该餐桌处于已经预定或者就餐状态时,不能进行预定,并给出相应提示 4.5.2思路分析 根据显示界面,要考虑以下两种状态 检测餐桌 ...

  4. IP分类与子网划分

    1.IP地址的格式  每一类地址都由两个固定长度的字段组成: (1)网络号 net-id:它标志主机(或路由器)所连接到的网络 (2)主机号 host-id:它标志该主机(或路由器).   最大可指派 ...

  5. JS 学习笔记(一)常用的字符串去重方法

    要求:从输入框中输入一串字符,按回车后输出去重后的字符串 方法一: <body> <input type="text" id="input" ...

  6. VP记录

    预计在最后的日子里适量VP 简单记录一下 CF 1037 Link 上来秒了ABCD,很快啊 A是二进制拆分,B是一眼贪心,C是一个非常简单且好写的dp D把边遍历顺序按照所需的bfs顺序排序,最后比 ...

  7. Jekyll于windows中使用

    安装 安装Ruby http://rubyinstaller.org/downloads/ 于其中选择最新的带dev套件的. 在安装时,安装目录不能有空格,检查是否已经安装成功 ruby -v gem ...

  8. mysql网上知识

    MySQL学习笔记 登录和退出MySQL服务器 # 登录MySQL $ mysql -u root -p12345612 # 退出MySQL数据库服务器 exit; 基本语法 -- 显示所有数据库 s ...

  9. VBA粗犷整理

    PART1: 三.查找 1.从某一行向上/下找到第一个不为空的行 intRowPntEnd = ActiveSheet.Cells(intRowPntStart, intColPnt).End(xlD ...

  10. C#怎么在生成解决方案的过程中执行perl脚本(C#早期绑定)

    转载 怎么在生成解决方案的过程中执行perl脚本 早期绑定在编译期间识别并检查方法.属性.函数,并在应用程序执行之前执行其他优化.在这个绑定中,编译器已经知道它是什么类型的对象以及它拥有的方法或属性. ...