图片实现缩放的代码有哪些?

图片缩放通常涉及到编程和特定的编程语言。这里提供几种主流编程语言的图片缩放实现方法:

  1. Python(使用PIL库):

 
  

python复制代码

from PIL import Image
def resize_image(input_image_path, output_image_path, size):
original_image = Image.open(input_image_path)
width, height = original_image.size
print(f"The original image size is {width} wide x {height} tall")
resized_image = original_image.resize(size)
width, height = resized_image.size
print(f"The resized image size is {width} wide x {height} tall")
resized_image.show()
resized_image.save(output_image_path)
# 使用方法
resize_image('original.jpg', 'resized.jpg', (800, 600))
  1. JavaScript(使用canvas):

 
  

javascript复制代码

function resizeImage(inputImage, outputImage, maxSize) {
var input = document.createElement("img");
input.src = inputImage;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var ratio = Math.min(maxSize / input.width, maxSize / input.height);
var newWidth = input.width * ratio;
var newHeight = input.height * ratio;
canvas.width = newWidth;
canvas.height = newHeight;
ctx.drawImage(input, 0, 0, newWidth, newHeight);
var output = canvas.toDataURL("image/jpeg", 1.0);
document.write('');
}
// 使用方法
resizeImage('original.jpg', 'resized.jpg', 800);
  1. Java(使用JavaFX的ImageView组件):

 
  

java复制代码

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.geometry.Rectangle2D;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import javafx.util.converter.NumberStringConverter;
import javafx.geometry.*;
import javafx.*;
import java.*;
import javax.*;
import javafx.scene.*;
import javafx.scene.image.*;
import javafx.scene.paint.*;
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.layout.*;
import javafx.geometry.*;
import javafx.*;
import java.*;
import javax.*;

你可能感兴趣的:(python,前端,javascript)