Created
December 2, 2016 17:00
-
-
Save weverb2/5f0d6e3621801493f9ef84e6c7a90d6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.graphics.Bitmap | |
import android.graphics.Color | |
import com.google.zxing.BarcodeFormat | |
import com.google.zxing.EncodeHintType | |
import com.google.zxing.MultiFormatWriter | |
import com.google.zxing.WriterException | |
import com.google.zxing.common.BitMatrix | |
object BarcodeUtil { | |
@Throws(WriterException::class) | |
fun barcodeFromString(barcodeFormat: BarcodeFormat, str: String, width: Int, height: Int): Bitmap? { | |
val result: BitMatrix | |
val stride: Int | |
try { | |
val hints = mapOf(EncodeHintType.MARGIN to 0) | |
if (barcodeFormat == BarcodeFormat.QR_CODE) { | |
val square = Math.min(width, height) | |
stride = square | |
result = MultiFormatWriter().encode(str, barcodeFormat, square, square, hints) | |
} else { | |
stride = width | |
result = MultiFormatWriter().encode(str, barcodeFormat, width, height, hints) | |
} | |
} catch (iae: IllegalArgumentException) { | |
// Unsupported format | |
return null | |
} | |
val w = result.width | |
val h = result.height | |
val pixels = IntArray(w * h) | |
for (y in 0..h - 1) { | |
val offset = y * w | |
for (x in 0..w - 1) { | |
pixels[offset + x] = if (result.get(x, y)) { | |
Color.BLACK | |
} else { | |
Color.WHITE | |
} | |
} | |
} | |
val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) | |
bitmap.setPixels(pixels, 0, stride, 0, 0, w, h) | |
return bitmap | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment