引入
<dependencies>
<!-- ZXing -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
服务类
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.*;
@Service
public class QRCodeReaderService {
public List<String> readMultipleQRCodes(MultipartFile file) throws IOException, NotFoundException {
// 将 MultipartFile 转换为 BufferedImage
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Map<DecodeHintType, Object> hints = new HashMap<>();
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, Collections.singletonList(BarcodeFormat.QR_CODE));
MultiFormatReader multiFormatReader = new MultiFormatReader();
GenericMultipleBarcodeReader reader = new GenericMultipleBarcodeReader(multiFormatReader);
Result[] results = reader.decodeMultiple(bitmap, hints);
List<String> qrContents = new ArrayList<>();
if (results != null) {
for (Result result : results) {
qrContents.add(result.getText());
}
}
return qrContents;
}
}
接口
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@RestController
public class QRCodeController {
@Autowired
private QRCodeReaderService qrCodeReaderService;
@PostMapping("/upload")
public ResponseEntity<List<String>> uploadQRCodeImage(@RequestParam("file") MultipartFile file) {
try {
List<String> qrCodes = qrCodeReaderService.readMultipleQRCodes(file);
return ResponseEntity.ok(qrCodes);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(500).body(Collections.emptyList());
}
}
}
结果