安卓-二维码生成器API



我正在尝试从我的应用程序生成一些QR,但我看到有很多类型的QR,如联系人、Wi-Fi等。我想知道是否有免费的API或库可以实现这一点,我看到有网站已经在生成它,所以我想知道Android是否有API或库可以使用。

我检查过的:

http://goqr.me/api

Zxing

但我不确定是否有一个功能可以说"好吧,我想要一个联系人的二维码,这样我就可以添加它的所有信息。">

使用ZXing生成二维码

在应用程序级build.gradle文件中添加以下ZXing核心依赖项。

implementation 'com.google.zxing:core:3.4.0'

生成512x512像素WiFi二维码的示例代码。您可以在ImageView中设置生成的位图。

fun getQrCodeBitmap(ssid: String, password: String): Bitmap {
val size = 512 //pixels
val qrCodeContent = "WIFI:S:$ssid;T:WPA;P:$password;;"
val hints = hashMapOf<EncodeHintType, Int>().also { it[EncodeHintType.MARGIN] = 1 } // Make the QR code buffer border narrower
val bits = QRCodeWriter().encode(qrCodeContent, BarcodeFormat.QR_CODE, size, size) 
return Bitmap.createBitmap(size, size, Bitmap.Config.RGB_565).also {
for (x in 0 until size) {
for (y in 0 until size) {
it.setPixel(x, y, if (bits[x, y]) Color.BLACK else Color.WHITE)
}
}
}
}

要生成其他类型的二维码,如短信、VCard等,您可以查看这个有用的ZXingWiki。

使用Google Mobile Vision API扫描二维码

将以下GMS依赖项添加到应用程序级别build.gradle

implementation 'com.google.android.gms:play-services-vision:20.1.2'

步骤1:设置条形码处理器回调。

private val processor = object : Detector.Processor<Barcode> {

override fun receiveDetections(detections: Detector.Detections<Barcode>?) {
detections?.apply {
if (detectedItems.isNotEmpty()) {
val qr = detectedItems.valueAt(0)
// Parses the WiFi format for you and gives the field values directly
// Similarly you can do qr.sms for SMS QR code etc.
qr.wifi?.let { 
Log.d(TAG, "SSID: ${it.ssid}, Password: ${it.password}")
}
}
}
}
override fun release() {}
} 

步骤2:使用条形码处理器回调设置BardcodeDetector,并将其添加到CameraSource中,如下所示。不要忘记在运行时检查Manifest.permission.CAMERA,并将其添加到您的AndroidManifest.xml中。

private fun setupCameraView() {
if (ContextCompat.checkSelfPermission(requireContext(), android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
BarcodeDetector.Builder(requireContext()).setBarcodeFormats(QR_CODE).build().apply {
setProcessor(processor)
if (!isOperational) {
Log.d(TAG, "Native QR detector dependencies not available!")
return
}
cameraSource = CameraSource.Builder(requireContext(), this).setAutoFocusEnabled(true)
.setFacing(CameraSource.CAMERA_FACING_BACK).build()
}
} else {
// Request camers permission from user
// Add <uses-permission android:name="android.permission.CAMERA" /> to AndroidManifest.xml
}
}

步骤3:在布局中添加一个SurfaceView以承载CameraSource

<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" /> 

第4步:创建回调以在创建/销毁曲面时启动和停止CameraSource

private val callback = object : SurfaceHolder.Callback {
override fun surfaceCreated(holder: SurfaceHolder) {
// Ideally, you should check the condition somewhere 
// before inflating the layout which contains the SurfaceView
if (isPlayServicesAvailable(requireActivity()))
cameraSource?.start(holder)
} 
override fun surfaceDestroyed(holder: SurfaceHolder) {
cameraSource?.stop()
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { }
}

// Helper method to check if Google Play Services are up to-date on the phone
fun isPlayServicesAvailable(activity: Activity): Boolean {
val code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(applicationContext)
if (code != ConnectionResult.SUCCESS) {
GoogleApiAvailability.getInstance().getErrorDialog(activity, code, code).show()
return false
}
return true
}

第5步:将所有内容与生命周期方法链接在一起。

// Create camera source and attach surface view callback to surface holder
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_camera_sheet, container, false).also {
setupCamera()
it.surfaceView.holder.addCallback(callback)
}
}
// Free up camera source resources
override fun onDestroy() {
super.onDestroy()
cameraSource?.release()
}

U可以使用QRCodeWriter类通过Zxing生成QR,并使用encode()函数,其中第一个参数是QR要保存的实际数据。自定义示例:

val qrCodeData: String = "data"
val bitMatrix = QRCodeWriter().encode(
String(
qrCodeData.toByteArray(charset(CHARSET)),
Charset.forName(CHARSET)
),
BarcodeFormat.QR_CODE,
size,
size,
hints
)

其中hints也是这个库的一部分,可以在EncodeHintType中找到。

然后u必须生成可以在例如ImageView中显示的Bitmap

val bitmap = Bitmap.createBitmap(
size,
size,
Bitmap.Config.ARGB_8888
)
for (x in 0 until size) {
for (y in 0 until size) {
val fillColor = if (bitMatrix[x, y]) Color.BLACK else Color.WHITE
bitmap.setPixel(x, y, fillColor) // <-- color ur QR to default black and white
}
}

对于vCard,我可以推荐以下内容:如何使用java创建vcf文件?

ZXing正确的方式〔2021更新〕

依赖Gradle Scripts/build.gradle(Module:app)

implementation 'com.journeyapps:zxing-android-embedded:4.3.0'

代码

import android.util.Log;
import android.graphics.Bitmap;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.journeyapps.barcodescanner.BarcodeEncoder;
public static Bitmap generateQR(String content, int size) {
Bitmap bitmap = null;
try {
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
bitmap = barcodeEncoder.encodeBitmap(content,
BarcodeFormat.QR_CODE, size, size);
} catch (WriterException e) {
Log.e("generateQR()", e.getMessage());
}
return bitmap;
}

更多详情请点击:dx.dragan.ba/qr-creation-android/

如果使用zxing-android-embedded

dependencies {
implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
}

你可以缩短

val barcodeEncoder = BarcodeEncoder()
val bitmap = barcodeEncoder.encodeBitmap(content, BarcodeFormat.QR_CODE, 512, 512)
your_image_view.setImageBitmap(bitmap)

相关内容

  • 没有找到相关文章

最新更新