【编程之美09】把照片尺寸变成都不大于肾6分辨率的大小。

程序员的惊奇之处就是别人用工具学习怎样做的时候,你早已用你的几行代码实现了自己想做的事情~


你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iPhone6 分辨率的大小。

“编程之美,让你爱上编程的美。”

挑战下面编程题目,

一起体验编程的乐趣!

本期题目:

你有一个目录,装了很多照片,把它们的尺寸变成都不大于 iphone6分辨率的大小。

编程之美独有福利:

这个栏目就是为了培养大家编程动手习惯并且提高编程能力的一个平台,我们现如今给参与这个栏目的提供如下福利:
  • 源码分享
  • 每周评比编程之星(奖励牛客大礼包一份,这回是充满惊喜,每个大礼包里不一定包括什么)
  • 企业实习工作机会
  • 独家名誉及待遇
  • 参与开源项目
  • 定期的分享讲座
等等等等!我们想进行一些不一样的玩法,让学习变得更有趣!无论你找到工作与否,即使是已经工作了,你也要有一个练手交流的平台~


当然啦,重要的是来练习自己的编程能力,分享代码,交流技术的过程,这个过程中,你提升的不只是一点点~

为了让牛友能够更高效,更好的学习,特意为大家建了一个群:牛客编程之美源码群 595665246,只给真正想参与这个栏目和真正想学习的人开放,会在群里定期分享源码,只让真正想学习的人来参加,所以只有参与栏目(在本栏目下发出自己的代码的)才能加,加的时候备注一下牛客昵称~

编程之星

每一期的玩法都不一样!每一期的编程之星的规则也不一样~~重要的是人人都参与进来
本期编程之星评比规则:由工程师来评选~

注:因为目前群成员比较多,本着只让真正想参与的人进来的原则,可能后期会整理群啦,对这个没有兴趣的我们就会把位置让给真正有兴趣参加的人啦~

栏目介绍

编程之美,是牛客网推出的新栏目,每周推出一个项目供大家练手讨论交流。

如果你有想实现的项目问题,欢迎私信牛妹~

另外!另外!如果有好玩的项目题目可以私信牛妹,一经采用有奖励哦~~

如果你有写博客或者公众号的习惯,也欢迎加牛妹qq:1037532015私信。

参考代码:
#!/usr/bin/env python 
 # coding=utf-8 
   from PIL import Image 
   org = Image.open('./origin.jpg') 
 org = org.resize((50,50), Image.ANTIALIAS) 
 org.save('rst', 'jpeg') 

全部评论
import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashSet; import java.util.Set; import javax.imageio.ImageIO; public class ImageUtil { private static Set<String> suffixSet = new HashSet<>(); // 能处理的图片格式集合 static { suffixSet.add("jpg"); suffixSet.add("png"); suffixSet.add("bmp"); } /** * 将目录中的所有图片适配为iphone6屏幕尺寸并输出到新的目录中 * @param inputPath 输入图片目录 * @param outputPath 输出图片目录 */ public static void adaptImagesToIphone(String inputPath, String outputPath) { File inPath = new File(inputPath); File outPath = new File(outputPath); File[] files = inPath.listFiles(); if (files.length != 0) { for (File in : files) { File out = new File(outPath + "\\" + in.getName()); adaptImageToIphone(in, out); } } } /** * 将图片适配为iphone6屏幕尺寸并输出新的图片 * @param inputPath 输入图片绝对路径 * @param outputPath 输出图片绝对路径 * @return */ public static boolean adaptImageToIphone(String inputPath, String outputPath) { return adaptImageToIphone(new File(inputPath), new File(outputPath)); } private static boolean adaptImageToIphone(File inputFile, File outputFile) { return adaptImage(inputFile, outputFile, (image) -> { // 简单粗暴直接将原图缩放为iPhone6的屏幕尺寸 int width = 750; int height = 1334; BufferedImage newImage = new BufferedImage(width, height, image.getType()); Graphics g = newImage.getGraphics(); g.drawImage(image, 0, 0, width, height, null); g.dispose(); return newImage; }); } /* * 将图片按照指定策略进行处理后输出 * @param inputFilePath 输入图片绝对路径 * @param outputFilePath 输出图片绝对路径 * @param strategy 图片处理策略函数 * @return */ private static boolean adaptImage(File fi, File fo, AdaptStrategy strategy) { try { String filePath = fi.getPath(); if (filePath.contains(".")) { String[] params = filePath.split("\\."); String fileFormat = params[params.length - 1].toLowerCase(); if (suffixSet.contains(fileFormat)) { // 按照文件扩展名判断是否能处理 BufferedImage image = ImageIO.read(fi); // 读取原图像 BufferedImage newImage = strategy.adapt(image); // 按照策略处理图像 ImageIO.write(newImage, fileFormat, fo); // 将新图像写入文件 return true; } } return false; } catch (Exception e) { e.printStackTrace(); return false; } } @FunctionalInterface interface AdaptStrategy { BufferedImage adapt(BufferedImage image); } public static void main(String[] args) { String inputPath = "G:\\testimg\\"; String ouputPath = "G:\\testimg\\new\\"; long start = System.currentTimeMillis(); adaptImagesToIphone(inputPath, ouputPath); long end = System.currentTimeMillis(); System.out.println("duration=" + (end - start) + "ms"); } }
点赞
送花
回复
分享
发布于 2016-12-23 21:13
package nowcoder.pictureZoom; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import javax.imageio.ImageIO; public class ImageOperater { /** * 左上方 */ public static final int LEFT_UPPER = 1; /** * 右上方 */ public static final int RIGHT_UPPER = 2; /** * 左下方 */ public static final int LEFT_LOWER = 3; /** * 右下方 */ public static final int RIGHT_LOWER = 4; /** * 中间 */ public static final int CENTER = 5; private BufferedImage image; private String path; private String type; /** * 用File构造一个ImageOperater对象 * @param file 图像文File对象 */ public ImageOperater(File file) { try { this.image = ImageIO.read(file); this.path = file.getAbsolutePath(); this.type = getType(this.path); } catch (IOException e) { e.printStackTrace(); } } /** * 用路径构造一个ImageOperater对象 * @param path 图像文件路径 */ public ImageOperater(String path) { this.path = path; readImage(this.path); this.type = getType(this.path); } /** * 使用路径构造BufferedImage对象 * @param path 图像文件路径 */ private void readImage(String path){ try { this.image = ImageIO.read(new File(path)); } catch (IOException e) { e.printStackTrace(); } } /** * 获取文件类型 * @param path * @return */ private String getType(String path){ return path.substring(path.lastIndexOf(".")+1); } /** * 等比放大图片 */ public ImageOperater blowUpImageEqualProportion(int ratio){ //构造一个按原图放大的图片 BufferedImage image = new BufferedImage(this.image.getWidth()*ratio, this.image.getHeight()*ratio, BufferedImage.TYPE_INT_RGB); //把原图画到构造的图片上 image.getGraphics().drawImage(this.image,0,0, this.image.getWidth()*ratio, this.image.getHeight()*ratio, null); this.image = image; //返回ImageOperater对象,以便链式处理图片 return this; } /** * 等比放大图片 */ public ImageOperater reduceEqualProportion(int ratio){ //构造一个按原图缩放的图片 BufferedImage image = new BufferedImage(this.image.getWidth()/ratio, this.image.getHeight()/ratio, BufferedImage.TYPE_INT_RGB); //把原图画到构造的图片上 image.getGraphics().drawImage(this.image,0,0,this.image.getWidth()/ratio, this.image.getHeight()/ratio, null); this.image = image; //返回ImageOperater对象,以便链式处理图片 return this; } /** * 缩放到指定大小 */ public ImageOperater cutNotEqualProportion(int width,int height){ //构造一个指定大小的图片 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //把原图画到构造的图片上 image.getGraphics().drawImage(this.image,0,0,width, height,null); this.image = image; //返回ImageOperater对象,以便链式处理图片 return this; } /** * 添加水印 * @param waterMarkFile 水印文件 * @param POSITION 添加水印的位置 * @return */ public ImageOperater addWatermark(File waterMarkFile,int POSITION){ BufferedImage waterMark = null; try { waterMark = ImageIO.read(waterMarkFile); } catch (IOException e) { e.printStackTrace(); } //构造一个和原图一样大小的图片 BufferedImage image = new BufferedImage(this.image.getWidth(), this.image.getHeight(), BufferedImage.TYPE_INT_RGB); //把原图画到构造的图片上 image.getGraphics().drawImage(this.image,0,0,this.image.getWidth(), this.image.getHeight(), null); switch (POSITION) { case LEFT_UPPER: image.getGraphics().drawImage(waterMark,0,0, waterMark.getWidth(), waterMark.getHeight(),null); break; case RIGHT_UPPER: image.getGraphics().drawImage(waterMark,image.getWidth()-waterMark.getWidth(),0, waterMark.getWidth(), waterMark.getHeight(),null); break; case LEFT_LOWER: image.getGraphics().drawImage(waterMark,0,image.getHeight()-waterMark.getHeight(), waterMark.getWidth(), waterMark.getHeight(),null); break; case RIGHT_LOWER: image.getGraphics().drawImage(waterMark,image.getWidth()-waterMark.getWidth(), image.getHeight()-waterMark.getHeight(), waterMark.getWidth(), waterMark.getHeight(),null); break; case CENTER: image.getGraphics().drawImage(waterMark,(image.getWidth()-waterMark.getWidth())/2, (image.getHeight()-waterMark.getHeight())/2, waterMark.getWidth(), waterMark.getHeight(),null); break; default: throw new RuntimeException("指定位置不正确!"); } this.image = image; return this; } /** * 覆盖原图保存 */ public ImageOperater save(){ FileOutputStream fos = null; try { fos = new FileOutputStream(new File(path)); //保存文件 ImageIO.write(image, this.type, fos); } catch (Exception e) { e.printStackTrace(); } //关闭流 try { if(fos!=null){ fos.close(); } } catch (IOException e) { e.printStackTrace(); } return this; } /** * 保存到指定路径 * @param path */ public ImageOperater save(String path,String name){ FileOutputStream fos = null; File file = new File(path); //如果路径不存在,尝试创建文件夹 if(!file.exists()){ file.mkdirs(); } //如果路径不是文件则抛出异常 if(file.isFile()){ throw new RuntimeException("指定路径不是文件夹!"); } file = new File(file, name+"."+type); try { fos = new FileOutputStream(file); ImageIO.write(image, this.type, fos); } catch (Exception e) { e.printStackTrace(); } //关闭流 try { if(fos!=null){ fos.close(); } } catch (IOException e) { e.printStackTrace(); } return this; } /** * 保存到指定路径(绝对路径,相对路径) * @param path */ public ImageOperater save(String path,String relativePath,String name){ return save(path+File.pathSeparator+relativePath,name); } /** * 获取BufferedImage对象 * @return */ public BufferedImage getImage(){ return this.image; } /** * 获取图片绝对路径 * @return */ public String getAbsolutePath(){ return this.path; } /** * 获取文件类型 * @return */ public String getImageType(){ return this.type; } } Client: package nowcoder.pictureZoom; import java.io.File; public class Client { public static void main(String[] args) { File file = new File("D:/0.jpg"); File watermark = new File("D:/1.png"); ImageOperater operater = new ImageOperater(file); operater.reduceEqualProportion(3) //缩小到三分之一并保存 .save("D:","1") //在右上方加上水印并保存 .addWatermark(watermark, ImageOperater.RIGHT_UPPER) .save("D:","2") //下面做个骰子 .addWatermark(watermark, ImageOperater.LEFT_UPPER) .addWatermark(watermark, ImageOperater.LEFT_LOWER) .addWatermark(watermark, ImageOperater.RIGHT_LOWER) .addWatermark(watermark, ImageOperater.CENTER) .save("D:","3"); operater = new ImageOperater(file); //当然你也可以按照自己的尺寸剪裁 operater.cutNotEqualProportion(200, 300).save("D:", "cut"); File folder = new File("D:/pic"); Batch(folder, 200, 200); } public static void Batch(File file,int weidth,int heigth){ if(!file.isDirectory()){ return; } for(File f:file.listFiles()){ if(f.isFile()){ ImageOperater operater = new ImageOperater(f); operater.cutNotEqualProportion(weidth, heigth).save(); }else{ //递归处理 Batch(f,weidth,heigth); } } } } 原始文件: 处理后: 这次顺便也把之前一期给头像加个1也一起做了
点赞
送花
回复
分享
发布于 2017-01-03 21:09
滴滴
校招火热招聘中
官网直投
#!/usr/bin/env python # -*- encoding: utf-8 -*- # @Date : 2015-03-08 20:15:47 # @Author : NSSimacer # @Email : wuxiaoqiang1020@gmail.com # @Version : 1.0 import cv2 import os def resize_images(base_dir, size=(1334, 750)): ''' 更改图片尺寸,使之不高于 iPhone x 的分辨率,默认参数是 iPhone 6 的分辨率,调用的时候可以更改为任意分辨率参数 ''' files = os.listdir(base_dir) for f in files: # 根据文件后缀判断是否文件是否为图片 # if f[f.rfind('.') + 1:] in ['jpg', 'png', 'bmp', 'gif', 'jpeg']: if os.path.splitext(f)[1][1:] in ['jpg', 'png', 'bmp', 'gif', 'jpeg']: img = cv2.imread(base_dir + f) img_size = img.shape[:2] # 获取图片的尺寸 if 0 < img_size[0] <= size[0] and 0 < img_size[1] <= size[1]: size = img_size else: img = cv2.resize(img, size) # 更改图片尺寸 cv2.imwrite(base_dir + 'resized_' + f, img) if __name__ == '__main__': base_dir = 'iPhone6/' # 调整成 iPhone 6 的分辨率 resize_images(base_dir) # 传入参数,调整成 iPhone 5 的分辨率 resize_images(base_dir, size=(1136, 640))
点赞
送花
回复
分享
发布于 2016-12-23 14:40

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务