java 如何生成带有徽标的二维码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35104305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate QR code with logo inside it?
提问by Huitarheroherohero
I am developing the application for Android devices. I want to generate QR code with logo inside it.
我正在为 Android 设备开发应用程序。我想生成带有徽标的二维码。
With ZXing
I know how to generate simple QR codes like this one:
But I want to generate QR code with logo inside it.
So I want to get something like this:
Is there any way to do it? I have no idea how to do it. Could you help me please? May there is some ready library or example of how to do it.
有什么办法吗?我不知道该怎么做。请问你能帮帮我吗?可能有一些现成的图书馆或如何做到这一点的例子。
Thank you!
谢谢!
采纳答案by Let'sRefactor
You can add your logo it as an Image Overlaylike
您可以将徽标添加为图像叠加,例如
public BufferedImage getQRCodeWithOverlay(BufferedImage qrcode)
{
BufferedImage scaledOverlay = scaleOverlay(qrcode);
Integer deltaHeight = qrcode.getHeight() - scaledOverlay.getHeight();
Integer deltaWidth = qrcode.getWidth() - scaledOverlay.getWidth();
BufferedImage combined = new BufferedImage(qrcode.getWidth(), qrcode.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D)combined.getGraphics();
g2.drawImage(qrcode, 0, 0, null);
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, overlayTransparency));
g2.drawImage(scaledOverlay, Math.round(deltaWidth/2), Math.round(deltaHeight/2), null);
return combined;
}
private BufferedImage scaleOverlay(BufferedImage qrcode)
{
Integer scaledWidth = Math.round(qrcode.getWidth() * overlayToQRCodeRatio);
Integer scaledHeight = Math.round(qrcode.getHeight() * overlayToQRCodeRatio);
BufferedImage imageBuff = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);
Graphics g = imageBuff.createGraphics();
g.drawImage(overlay.getScaledInstance(scaledWidth, scaledHeight, BufferedImage.SCALE_SMOOTH), 0, 0, new Color(0,0,0), null);
g.dispose();
return imageBuff;
}
回答by Paul Spiesberger
I created the following Kotlin Extention, which adds a Bitmap to the centre of another Bitmap:
我创建了以下 Kotlin 扩展,它将位图添加到另一个位图的中心:
fun Bitmap.addOverlayToCenter(overlayBitmap: Bitmap): Bitmap {
val bitmap2Width = overlayBitmap.width
val bitmap2Height = overlayBitmap.height
val marginLeft = (this.width * 0.5 - bitmap2Width * 0.5).toFloat()
val marginTop = (this.height * 0.5 - bitmap2Height * 0.5).toFloat()
val canvas = Canvas(this)
canvas.drawBitmap(this, Matrix(), null)
canvas.drawBitmap(overlayBitmap, marginLeft, marginTop, null)
return this
}
Can find my full solution here.