Java는 원격 네트워크 이미지 파일 스트림을 획득하여 압축하고 로컬에 저장합니다.
java는 원격 네트워크에서 이미지 파일 스트림을 가져와 압축한 후 로컬에 저장합니다
1. 원격 네트워크에서 이미지 가져오기
/** * 根据地址获得数据的字节流 * * @param strUrl * 网络连接地址 * @return */ public static byte[] getImageFromNetByUrl(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据 byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据 return btImg; } catch (Exception e) { e.printStackTrace(); } return null; }
/** * 根据地址获得数据的字节流 * * @param strUrl * 本地连接地址 * @return */ public static byte[] getImageFromLocalByUrl(String strUrl) { try { File imageFile = new File(strUrl); InputStream inStream = new FileInputStream(imageFile); byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据 return btImg; } catch (Exception e) { e.printStackTrace(); } return null; }
/** * 从输入流中获取数据 * * @param inStream * 输入流 * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[10240]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); }
2. 네트워크 읽기 파일을 로컬 파일로 변환
byte[] btImg1 = ImageUtil.getImageFromNetByUrl(fileUrl1); if (null != btImg1 && btImg1.length > 0) { logger.debug("读取到:" + btImg1.length + " 字节"); ImageUtil.writeImageToDisk(btImg1, fileZipUrl1); } else { logger.debug("没有从该连接获得内容"); } byte[] btImg2 = ImageUtil.getImageFromNetByUrl(fileUrl2); if (null != btImg2 && btImg2.length > 0) { logger.debug("读取到:" + btImg2.length + " 字节"); ImageUtil.writeImageToDisk(btImg2, fileZipUrl2); } else { logger.debug("没有从该连接获得内容"); }
/** * 将图片写入到磁盘 * * @param img * 图片数据流 * @param fileName * 文件保存时的名称 */ public static void writeImageToDisk(byte[] img, String zipImageUrl) { try { File file = new File(zipImageUrl); FileOutputStream fops = new FileOutputStream(file); fops.write(img); fops.flush(); fops.close(); System.out.println("图片已经写入"+zipImageUrl); } catch (Exception e) { e.printStackTrace(); } }
3. 로컬 이미지 압축
import java.io.*; import java.util.Date; import java.awt.*; import java.awt.image.*; import javax.imageio.ImageIO; import com.sun.image.codec.jpeg.*; /** * 图片压缩处理 */ public class ImgCompress { private Image img; private int width; private int height; /** * 构造函数 */ public ImgCompress(String fileName) throws IOException { File file = new File(fileName);// 读入文件 img = ImageIO.read(file); // 构造Image对象 width = img.getWidth(null); // 得到源图宽 height = img.getHeight(null); // 得到源图长 } /** * 按照宽度还是高度进行压缩 * @param w int 最大宽度 * @param h int 最大高度 */ public void resizeFix(int w, int h) throws IOException { if (width / height > w / h) { resizeByWidth(w); } else { resizeByHeight(h); } } /** * 以宽度为基准,等比例放缩图片 * @param w int 新宽度 */ public void resizeByWidth(int w) throws IOException { int h = (int) (height * w / width); resize(w, h); } /** * 以高度为基准,等比例缩放图片 * @param h int 新高度 */ public void resizeByHeight(int h) throws IOException { int w = (int) (width * h / height); resize(w, h); } /** * 强制压缩/放大图片到固定的大小 * @param w int 新宽度 * @param h int 新高度 */ public void resize(int w, int h) throws IOException { // SCALE_SMOOTH 的缩略算法 生成缩略图片的平滑度的 优先级比速度高 生成的图片质量比较好 但速度慢 BufferedImage image = new BufferedImage(w, h,BufferedImage.TYPE_INT_RGB ); image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图 File destFile = new File("C:/Users/Administrator/Desktop/147.jpg"); FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流 // 可以正常实现bmp、png、gif转jpg JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); encoder.encode(image); // JPEG编码 out.close(); }
@SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { System.out.println("开始:" + new Date().toLocaleString()); ImgCompress imgCom = new ImgCompress("C:/Users/Administrator/Desktop/1479209533362.jpg"); imgCom.resizeFix(285, 380); System.out.println("结束:" + new Date().toLocaleString()); }
}
끝~

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Java의 난수 생성기 안내. 여기서는 예제를 통해 Java의 함수와 예제를 통해 두 가지 다른 생성기에 대해 설명합니다.

Java의 Weka 가이드. 여기에서는 소개, weka java 사용 방법, 플랫폼 유형 및 장점을 예제와 함께 설명합니다.

Java의 Smith Number 가이드. 여기서는 정의, Java에서 스미스 번호를 확인하는 방법에 대해 논의합니다. 코드 구현의 예.

이 기사에서는 가장 많이 묻는 Java Spring 면접 질문과 자세한 답변을 보관했습니다. 그래야 면접에 합격할 수 있습니다.

Java 8은 스트림 API를 소개하여 데이터 컬렉션을 처리하는 강력하고 표현적인 방법을 제공합니다. 그러나 스트림을 사용할 때 일반적인 질문은 다음과 같은 것입니다. 기존 루프는 조기 중단 또는 반환을 허용하지만 스트림의 Foreach 메소드는이 방법을 직접 지원하지 않습니다. 이 기사는 이유를 설명하고 스트림 처리 시스템에서 조기 종료를 구현하기위한 대체 방법을 탐색합니다. 추가 읽기 : Java Stream API 개선 스트림 foreach를 이해하십시오 Foreach 메소드는 스트림의 각 요소에서 하나의 작업을 수행하는 터미널 작동입니다. 디자인 의도입니다

Java의 TimeStamp to Date 안내. 여기서는 소개와 예제와 함께 Java에서 타임스탬프를 날짜로 변환하는 방법에 대해서도 설명합니다.

Java는 초보자와 숙련된 개발자 모두가 배울 수 있는 인기 있는 프로그래밍 언어입니다. 이 튜토리얼은 기본 개념부터 시작하여 고급 주제를 통해 진행됩니다. Java Development Kit를 설치한 후 간단한 "Hello, World!" 프로그램을 작성하여 프로그래밍을 연습할 수 있습니다. 코드를 이해한 후 명령 프롬프트를 사용하여 프로그램을 컴파일하고 실행하면 "Hello, World!"가 콘솔에 출력됩니다. Java를 배우면 프로그래밍 여정이 시작되고, 숙달이 깊어짐에 따라 더 복잡한 애플리케이션을 만들 수 있습니다.
