java 图片压缩 base64_图片改变像素,宽高,Base64编码处理

1.改变图片像素

private void setAlpha(String os) {

/**

* 增加测试项

* 读取图片,绘制成半透明,修改像素

*/

try {

ImageIcon imageIcon = new ImageIcon(os);

BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(),imageIcon.getIconHeight()

, BufferedImage.TYPE_USHORT_565_RGB);

Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();

g2D.drawImage(imageIcon.getImage(), 0, 0,

imageIcon.getImageObserver());

//循环每一个像素点,改变像素点的Alpha值

int alpha = 100;

System.out.println(System.currentTimeMillis());

for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {

for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {

int pixel = bufferedImage.getRGB(j2, j1);

int[] rgb = new int[3];

rgb[0] = (pixel & 0xff0000) >> 16;

rgb[1] = (pixel & 0xff00) >> 8;

rgb[2] = (pixel & 0xff);

pixel = ( (alpha + 1) << 24) | (pixel & 0x00ffffff);

bufferedImage.setRGB(j2, j1, pixel);

}

}

System.out.println(System.currentTimeMillis());

g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());

//生成图片为PNG

ImageIO.write(bufferedImage, "jpg", new File("C:\\Desktop\\1.jpg"));

}

catch (Exception e) {

e.printStackTrace();

}

}

2.改变图片宽高

/**

* 按指定高度 等比例缩放图片

*

* @param imageFile

* @param newPath

* @param newWidth 新图的宽度

* @throws IOException

*/

public static void zoomImageScale(File imageFile, String newPath, int newWidth) throws IOException {

System.out.println("------------------------------------------------------------------");

if(!imageFile.canRead())

return;

BufferedImage bufferedImage = ImageIO.read(imageFile);

if (null == bufferedImage)

return;

int originalWidth = bufferedImage.getWidth();

int originalHeight = bufferedImage.getHeight();

double scale = (double)originalWidth / (double)newWidth; // 缩放的比例

int newHeight = (int)(originalHeight / scale);

zoomImageUtils(imageFile, newPath, bufferedImage, newWidth, newHeight);

}

private static void zoomImageUtils(File imageFile, String newPath, BufferedImage bufferedImage, int width, int height)

throws IOException{

String suffix = StringUtils.substringAfterLast(imageFile.getName(), ".");

// 处理 png 背景变黑的问题

if(suffix != null && (suffix.trim().toLowerCase().endsWith("png") || suffix.trim().toLowerCase().endsWith("gif"))){

BufferedImage to= new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = to.createGraphics();

to = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);

g2d.dispose();

g2d = to.createGraphics();

System.out.println(width+"---"+height+"------------------------------------------------------------------"+Image.SCALE_AREA_AVERAGING);

Image from = bufferedImage.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING);

g2d.drawImage(from, 0, 0, null);

g2d.dispose();

ImageIO.write(to, suffix, new File(newPath));

}else{

System.out.println("------------------------------------------------------------------");

// 高质量压缩,其实对清晰度而言没有太多的帮助

BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

tag.getGraphics().drawImage(bufferedImage, 0, 0, width, height, null);

FileOutputStream out = new FileOutputStream(newPath); // 将图片写入 newPath

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);

JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);

jep.setQuality(1f, true); //压缩质量, 1 是最高值

encoder.encode(tag, jep);

out.close();

BufferedImage newImage = new BufferedImage(width, height, bufferedImage.getType());

Graphics g = newImage.getGraphics();

g.drawImage(bufferedImage, 0, 0, width, height, null);

g.dispose();

ImageIO.write(newImage, suffix, new File(newPath));

}

}

3.将图片文件转化为字节数组字符串,并对其进行Base64编码处理

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

import java.io.*;

/**

* @author hhr

* @create 2017-09-08

**/

public class Base64Test {

public static void main(String[] args) {

String strImg = GetImageStr();

System.out.println(strImg);

GenerateImage(strImg);

}

//图片转化成base64字符串

public static String GetImageStr() {//将图片文件转化为字节数组字符串,并对其进行Base64编码处理

String imgFile = "C:\\Users\\Administrator\\Desktop\\1.png";//待处理的图片

InputStream in = null;

byte[] data = null;

//读取图片字节数组

try {

in = new FileInputStream(imgFile);

data = new byte[in.available()];

in.read(data);

in.close();

} catch (IOException e) {

e.printStackTrace();

}

//对字节数组Base64编码

BASE64Encoder encoder = new BASE64Encoder();

return encoder.encode(data);//返回Base64编码过的字节数组字符串

}

//base64字符串转化成图片

public static boolean GenerateImage(String imgStr) { //对字节数组字符串进行Base64解码并生成图片

if (imgStr == null) //图像数据为空

return false;

BASE64Decoder decoder = new BASE64Decoder();

try {

//Base64解码

byte[] b = decoder.decodeBuffer(imgStr);

for (int i = 0; i < b.length; ++i) {

if (b[i] < 0) {//调整异常数据

b[i] += 256;

}

}

//生成jpeg图片

String imgFilePath = "C://222.jpg";//新生成的图片

OutputStream out = new FileOutputStream(imgFilePath);

out.write(b);

out.flush();

out.close();

return true;

} catch (Exception e) {

return false;

}

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/299094.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

WinAPI: 钩子回调函数之 MouseProc

为什么80%的码农都做不了架构师&#xff1f;>>> MouseProc(nCode: Integer; {}wParam: WPARAM; {}lParam: LPARAM {} ): LRESULT; {}//待续...转载于:https://my.oschina.net/hermer/blog/320962

shell对于字符串的操作

shell对于字符串的操作:以下为代码内容&#xff1a;得到长度 代码:%x"abcd" # 方法一 %expr length $x 4 # 方法二 %echo ${#x} 4 # 方法三 %expr "$x" : ".*" 4 # expr 的帮助 # STRING : REGEXP anchored pattern match of REGEXP in STRING…

方法参数修饰符in,out,ref

in&#xff0c;out&#xff0c;ref都可能作为方法参数据修饰符&#xff0c;从字面意思可就可以理解这三个关键字的含义&#xff0c;那用法是什么样子的呢&#xff0c;通过demo来看一下。定义一个引用类型Orderpublic class Order {public string OrderNo { get; set; }public o…

hdoj 1272

题目链接http://acm.hdu.edu.cn/showproblem.php?pid1272 并查集 1 #include <iostream>2 #include <algorithm>3 4 usingnamespacestd;5 6 intf[100001];7 booldis[100001];8 9 intFind(intx)10 {11 while( x !f[x] ){12 x f[x];13 }14 15 returnx;16 }17 18 int…

配置Tomcat的日志系统

成功配置tomcat的log4j日志系统&#xff0c;格式&#xff1a;HTML&#xff0b;每天以yyyy-mm-dd.log命名的日志文件一、引言&#xff1a;实习单位让用log4j配置webapp的日志系统&#xff0c;要求产生的日志文件是html格式&#xff0c;而且是每天以yyyy-mm-dd日期格式命名的日志…

python训练词库_在Python中训练NGramModel

首先,正如您对问题的评论中所指出的,如果培训/运行速度对您来说是一个问题,KenLM可能是更好的选择.此时nltk.model主要用于教育/原型设计,但它并不快.如果您仍然决定坚持使用NLTK,请继续阅读.我碰巧是模型分支中新的NgramModel代码的作者,我会尝试清楚地说明你可以测试代码并让…

内推!字节、阿里、网易火热招聘中,内推优筛简历,快人一步拿offer,真香!(送内推码)...

全世界只有3.14 % 的人关注了爆炸吧知识“金三银四”可谓招聘的黄金期。一方面&#xff0c;校园春招正如火如荼的进行中&#xff0c;另一方面&#xff0c;各大企业也纷纷启动了暑假实习招聘。对于2020届的同学来说&#xff0c;务必要利用好“应届生”这个身份&#xff0c;把握住…

如何将10进制转成16进制,又如何将16进制数转成10进制,C#和VB代码?

方法1&#xff1a; int d10; d.ToString("x") //或把x改为&#xff38;&#xff0c;&#xff0c;&#xff0c;就变成了&#xff11;&#xff16;位的字符串了&#xff0e; int xConvert.ToInt32(d.ToString("x"),16);&#xff0f;&a…

C#怎么测试静态方法?我给出了2种方案

问题假设有一个方法需要判断当前小时范围&#xff0c;代码如下&#xff1a;public class Class1 {public bool SomeMethod(){var hour DateTime.Now.Hour;if (hour > 9 && hour < 12){return true;}return false;} }但是&#xff0c;在做单元测试时&#xff0c;…

关于Tomcat5.5中EL表达式无效的解决办法

问题&#xff1a; 在Tomcat5.5中&#xff0c;JSP页中使用EL表达式输出信息&#xff0c;例如&#xff1a; <% page language”java” import”java.util.*” pageEncoding”UTF-8″%><html><head>EL表达式</head><body>${header["User-Agent…

c语言全局变量和局部变量问题汇总

1、局部变量是否能和全局变量重名&#xff1f; 答&#xff1a;能&#xff0c;局部会屏蔽全局。要用全局变量&#xff0c;须要使用"::" 局部变量能够与全局变量同名&#xff0c;在函数内引用这个变量时&#xff0c;会用到同名的局部变量&#xff0c;而不会用到全局变…

本科4篇顶会论文如何做到?清华特奖高天宇干货分享:我是这样写论文、做实验、与导师相处...

全世界只有3.14 % 的人关注了爆炸吧知识本科生&#xff0c;距离“科研”有多远&#xff1f;有人还处在“小朋友你是否有很多问号”的状态&#xff0c;但也有人本科就连发顶会文章&#xff0c;光环闪瞎众人。其中可有什么秘诀&#xff1f;清华本科特奖获得者、清华计算机大四学生…

java final 修改_“无法改变的设计”——浅谈Java中的final关键字

在Java中&#xff0c;final关键字可以用来修饰类、变量(包括成员变量和局部变量)、方法&#xff0c;下面从这三个方面分别说明。final方法当一个方法被final修饰时&#xff0c;表明这个方法不能被子类重写。下面程序试图重写final方法&#xff0c;将会引发编译错误。public cla…

数据库日志的说明

清日志 如 dump transaction 数据库名 with no_log --清除日志backup log 数据库名 with no_log --截断事务日志dbcc shrinkdatabase(数据库名,10) --收缩的数据库&#xff0c;空出10%的空间来 先执行上面两句&#xff0c;这两句比较快…

.NET 6 预览版 7 Released

.NET 6 预览版 7 ReleasedRichard 2021 年 8 月 10 日我们很高兴发布 .NET 6 Preview 7。这是我们进入&#xff08;两个&#xff09;发布候选 (RC) 期之前的最后一次预览版本。在我们放慢发布速度之前&#xff0c;团队经常加班夜战来保证最后一组功能。在这个版本中&#xff0c…

孝顺孝顺,孝不如顺

摘自西西河&#xff1a;http://www.ccthere.com/article/3044112&#xff0c;作者&#xff1a;抱朴仙人 刚说到一把年纪还要被老爹教育&#xff0c;忽然发现河里颇有几位难友&#xff0c;呵呵。 话说这个孝道&#xff0c;一直是包括“赡养”和“陪伴”两个方面的&#xff0c;也…

一致性 hash 算法( consistent hashing )

consistent hashing 算法早在 1997 年就在论文 Consistent hashing and random trees 中被提出&#xff0c;目前在cache 系统中应用越来越广泛&#xff1b; 1 基本场景 比如你有 N 个 cache 服务器&#xff08;后面简称 cache &#xff09;&#xff0c;那么如何将一个对象 obje…

复工之后,如何让自己的时间更值钱

全世界只有3.14 % 的人关注了爆炸吧知识时间最不偏私给任何人都是二十四小时时间也最偏私给任何人都不是二十四小时而如何让自己的时间更值钱以下公众号或许能给你一些启示赶快扫码关注吧&#xff01;RSS精选ID&#xff1a;KindleNewsRSS精选是一个专注于时间管理iOS相关及Kind…

selenium autoit java_Java+Selenium——AutoIt工具处理文件上传

关于文件上传&#xff0c;这边介绍一个第三方工具&#xff0c;叫AutoIt&#xff0c;简单来说&#xff0c;这个是一个能支持桌面GUI自动化的工具&#xff0c;它支持脚本语言编写。这里&#xff0c;我们用AutoIt来做文件上传的演示。在Selenium脚本中如果需要AutoIt来协助这个文件…

Blazor+Dapr+K8s微服务之开发环境调试

1 安装Dapr开发调试环境1.1 Dapr 完整安装模式不支持开发调试在上一篇随笔《BlazorDaprK8s微服务之服务调用》中&#xff0c;我们通过为每个微服务运行dapr run ….dotnet run命令&#xff0c;以自宿主的方式在本地开发环境成功运行了服务调用的例子。但是&#xff0c;这种运行…