分享一个项目中在用的图片处理工具类(图片缩放,旋转,画布格式,字节,image,bitmap转换等)
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转换等)的更多相关文章
- Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
Go/Python/Erlang编程语言对比分析及示例 本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...
- eclipse中将一个项目作为library导入另一个项目中
1. github上搜索viewpagerIndicator: https://github.com/JakeWharton/ViewPagerIndicator2. 下载zip包,解压,eclips ...
- 解决tomcat下面部署多个项目log4j的日志输出会集中输出到一个项目中的问题
在一次项目上线后,发现了一个奇怪的问题,经过对源码的阅读调试终于解决,具体经过是这样的: 问题描述:tomcat7下面部署多个项目,log4j的日志输出会集中输出到一个项目中,就算配置了日志文件的绝对 ...
- (转)最近一个项目中关于NGUI部分的总结(深度和drawCall)
在自己最近的一个项目中,软件的界面部分使用了NGUI来进行制作.在制作过程中,遇到了一些问题,也获取了一些经验,总结下来,作为日后的积累. 1.NGUI图集的使用. 此次是第一个自己正儿八经的制作完整 ...
- 当一个项目中同时存在webroot和webcontext时
当一个项目中同时存在webroot和webcontext时,注意一定要删除那些没在使用的.还有要发布其中一个想要的目录到服务器中,具体方法是 选择相应工程-----properties-----de ...
- VS编译linux项目生成静态库并在另一个项目中静态链接的方法
VS2017也推出很久了,在单位的时候写linux的服务端程序只能用vim,这让用惯了IDE的我很难受. 加上想自己撸一套linux上的轮子,决定用VS开工远程编写调试linux程序. 在window ...
- vs2010 C# 如何将类做成DLL 再从另一个项目中使用这个类
vs2010 C# 如何将类做成DLL 再从另一个项目中使用这个类 2011-10-20 12:00 486人阅读 评论(0) 收藏 举报 一.将类做成DLL 方法一: 你可以通过在命令行下用命令将以 ...
- 一个项目中:只能存在一个 WebMvcConfigurationSupport (静态文件失效之坑)
一个项目中:只能存在一个 WebMvcConfigurationSupport 在一个项目中WebMvcConfigurationSupport只能存在一个,多个的时候,只有一个会生效. 静态文件访问 ...
- 解决:一个项目中写多个包含main函数的源文件并分别调试运行
自己在学c++的时候,一个项目中的多个cpp文件默认不允许多个main函数的出现,但是通过选项操作能够指定单个cpp文件进行运行,如下: 1.此时我就想运行第二个cpp文件,我们只需要把其他的两个右键 ...
- 分享一个非常好用又好看的终端工具--Hyper (支持windows、MacOS、Linux)
分享一个非常好用又好看的终端工具--Hyper 官网地址: https://hyper.is/ 打开官网,选择对应版本安装即可:(可能网络原因,无法下载, 可以从我分享的链接下载 链接: https: ...
随机推荐
- POJ2104 K-th number (整体二分)
刚学了整体二分,用这种解法来解决这道题. 首先对于每个询问时可以二分解决的,这也是可以使用整体二分的前提.将原来的序列看成是插入操作,和询问操作和在一起根据值域进行二分.用树状数组来检验二分值. 1 ...
- Docker | 容器数据卷详解
什么是容器数据卷 从docker的理念说起,docker将应用和环境打包成一个镜像,运行镜像(生成容器)就可以访问服务了. 如果数据都存在容器中,那么删除容器,数据就会丢失!需求:数据可以持久化 My ...
- 给 hugo 博客添加搜索功能
起因 我的博客使用了 hugo 作为静态生成工具,自带的主题里也没有附带搜索功能.看来,还是得自己给博客添加一个搜索功能. 经过多方查找,从 Hugo Fast Search · GitHub 找到一 ...
- pod(九):污点taint 与容忍度tolerations
目录 一.系统环境 二.前言 三.污点taint 3.1 污点taint概览 3.2 给节点添加污点taint 四.容忍度tolerations 4.1 容忍度tolerations概览 4.2 设置 ...
- python uiautomator
电脑连接上一个手机或多个手机, 确保adb已经添加到环境变量中,执行下面的命令会自动安装本库所需要的设备端程序:uiautomator-server .atx-agent.openstf/minica ...
- js中对小数的计算
在js 的计算中如果涉及到小数的运算,那结果可不要想当然了,比如 0.1+0.2 的计算 var num1 = 0.1; var num2 = 0.2; console.log(num1+num2) ...
- NC-UClient下载安装应用详解
aliases: [] tags : " #NC " summary: [UClient下载安装NCC应用详解] product: [NCX] author : [yaenli] ...
- 使用 Spring Cloud LoadBalancer 实现客户端负载均衡
使用 Spring Cloud LoadBalancer 实现客户端负载均衡 作者:Grey 原文地址: 博客园:使用 Spring Cloud LoadBalancer 实现客户端负载均衡 CSDN ...
- ES6高级编程(一)
一.JavaScript概要 1.1.JavaScript组成 JavaScript主要由三部分构成,分别是ECMAScript.DOM与BOM ECMAScript定义了该语言的语法.类型.语句.关 ...
- Go语言核心36讲25
你好,我是郝林,今天我分享的主题是:测试的基本规则和流程(上). 你很棒,已经学完了本专栏最大的一个模块!这涉及了Go语言的所有内建数据类型,以及非常有特色的那些流程和语句. 你已经完全可以去独立编写 ...