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. 云原生分布式 PostgreSQL+Citus 集群在 Sentry 后端的实践

    优化一个分布式系统的吞吐能力,除了应用本身代码外,很大程度上是在优化它所依赖的中间件集群处理能力.如:kafka/redis/rabbitmq/postgresql/分布式存储(CephFS,Juic ...

  2. Dubbo-聊聊注册中心的设计

    前言 Dubbo源码阅读分享系列文章,欢迎大家关注点赞 SPI实现部分 Dubbo-SPI机制 Dubbo-Adaptive实现原理 Dubbo-Activate实现原理 Dubbo SPI-Wrap ...

  3. 7.websocket收发消息

    客户端主动向服务端发起websocket连接,服务端接收到连接后通过(握手) 客户端 websocket socket = new WebSocket('ws://127.0.0.1/ws/'); 服 ...

  4. 2流高手速成记(之六):从SpringBoot到SpringCloudAlibaba

    咱们接上回 2流高手速成记(之五):Springboot整合Shiro实现安全管理 - 14号程序员 - 博客园 (cnblogs.com) 身边常有朋友说:小项目用PHP.大项目用Java(这里绝无 ...

  5. SpringBoot 解决跨域问题代码

    package com.example.demo.gs; import org.springframework.context.annotation.Configuration; import jav ...

  6. 【单元测试】Junit 4(三)--Junit4断言

    1.0 前言 ​ 断言(assertion)是一种在程序中的一阶逻辑(如:一个结果为真或假的逻辑判断式),目的为了表示与验证软件开发者预期的结果--当程序执行到断言的位置时,对应的断言应该为真.若断言 ...

  7. Aspose.Cell和NPOI生成Excel文件2

    NPOI还是比较好用的,引用dll程序集即可 1创建workbook和工作流 HSSFWorkbook workbook = new HSSFWorkbook(); MemoryStream ms = ...

  8. GY91(MPU9250 + BMP280)惯性传感器开发指南

    目录 参考资料 I2C 设备ID 关键数据读取 MPU6500:读取加速度数据&换算单位 BMP280: 读取温度和气压信息 & 单位换算 推荐库 参考资料 参考资料说明: 用户手册时 ...

  9. javax.script.ScriptException: ReferenceError: "window" is not defined in security.js at line number 10

    使用jmeter执行加密登录接口的测试遇到的问题. 问题记录: 今天使用jmeter执行加密登录接口的测试,因为测试环境的应用包是以前的老版本(可能有两年了),所以需要替换加密文件:security. ...

  10. 如何避免由 Web 字体引起的布局偏移

    前言 一些布局上的完全加载前后的变化很容易解决:为动态元素预先分配正确的空间,在图像上使用宽度和高度属性,并优先考虑 HTML 文档中的可见元素.但是,导致布局偏移的还有一个难以解决的问题:无样式文本 ...