android 彩色圖片二值化轉(zhuǎn)可打印的點(diǎn)陣黑白圖

如何在手機(jī)上生成黑白圖傳讓電子墨水屏顯示出來?

一開始我在網(wǎng)上找了一個轉(zhuǎn)黑白圖片的方法,這個方法的邏輯是 用127做臨界值抄邀,來判斷灰度圖的灰度是否比他大,大就打白昼榛,小就打黑境肾,代碼和效果圖如下

 /**
     * 轉(zhuǎn)為二值圖像
     *
     * @param bmp 原圖bitmap
     *
     * @return
     */
    private fun convertToBMW(bmp: Bitmap, tmp:Int=130): Bitmap {
        val width = bmp.width // 獲取位圖的寬
        val height = bmp.height // 獲取位圖的高
        val pixels = IntArray(width * height) // 通過位圖的大小創(chuàng)建像素點(diǎn)數(shù)組
        // 設(shè)定二值化的域值,默認(rèn)值為100
        //tmp = 180;
        bmp.getPixels(pixels, 0, width, 0, 0, width, height)
        var alpha = 0xFF shl 24
        for (i in 0 until height) {
            for (j in 0 until width) {
                val grey = pixels[width * i + j]
                // 分離三原色
                alpha = grey and -0x1000000 shr 24
                var red = grey and 0x00FF0000 shr 16
                var green = grey and 0x0000FF00 shr 8
                var blue = grey and 0x000000FF
                if (red > tmp) {
                    red = 255
                } else {
                    red = 0
                }
                if (blue > tmp) {
                    blue = 255
                } else {
                    blue = 0
                }
                if (green > tmp) {
                    green = 255
                } else {
                    green = 0
                }
                pixels[width * i + j] = (alpha shl 24 or (red shl 16) or (green shl 8)
                        or blue)
                if (pixels[width * i + j] == -1) {
                    pixels[width * i + j] = -1
                } else {
                    pixels[width * i + j] = -16777216
                }
            }
        }
        // 新建圖片
        val newBmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        // 設(shè)置圖片數(shù)據(jù)
        newBmp.setPixels(pixels, 0, width, 0, 0, width, height)
        val bitmap = ThumbnailUtils.extractThumbnail(newBmp, width, height)
        imageView5.setImageBitmap(bitmap)
        return bitmap
    }
黑白效果圖

這種方式有一個問題胆屿,要么一大片白色要么一大片黑色奥喻,效果不是很理想。如果打印出來根本認(rèn)不出來這是誰非迹。

后面了解到Floyd-Steinberg算法环鲤,它是利用誤差的擴(kuò)散算法的Floyd-Steinberg抖動算法來對圖像進(jìn)行二值化處理。

例如憎兽,灰度如的灰度值為g冷离,誤差值為e。遍歷每個像素值纯命,灰度如果大于m(127西剥,或者像素灰度平均值,看你喜歡)亿汞,那么pixels【i】=#ffffffff瞭空,打白,e=g-255留夜;否則,打黑图甜,pixels【i】=#ff000000碍粥,e=g;然后黑毅,這個像素點(diǎn)的右邊嚼摩,下邊,和右下方的像素點(diǎn)矿瘦,對應(yīng)的加上3e/8,3e/8,e/4枕面。最后你的到的像素數(shù)組在轉(zhuǎn)成bitmap,就是抖動的單色圖了缚去。效果圖如下

    //抖動算法來對圖像進(jìn)行二值化處理
    private fun convertGreyImgByFloyd(img: Bitmap): Bitmap {
        val width = img.width         //獲取位圖的寬
        val height = img.height       //獲取位圖的高
        val pixels = IntArray(width * height) //通過位圖的大小創(chuàng)建像素點(diǎn)數(shù)組
        img.getPixels(pixels, 0, width, 0, 0, width, height)
        val gray = IntArray(height * width)
        for (i in 0 until height) {
            for (j in 0 until width) {
                val grey = pixels[width * i + j]
                val red = grey and 0x00FF0000 shr 16
                gray[width * i + j] = red
            }
        }
        var e = 0
        for (i in 0 until height) {
            for (j in 0 until width) {
                val g = gray[width * i + j]
                if (g >= 128) {
                    pixels[width * i + j] = -0x1
                    e = g - 255

                } else {
                    pixels[width * i + j] = -0x1000000
                    e = g - 0
                }
                if (j < width - 1 && i < height - 1) {
                    //右邊像素處理
                    gray[width * i + j + 1] += 3 * e / 8
                    //下
                    gray[width * (i + 1) + j] += 3 * e / 8
                    //右下
                    gray[width * (i + 1) + j + 1] += e / 4
                } else if (j == width - 1 && i < height - 1) {//靠右或靠下邊的像素的情況
                    //下方像素處理
                    gray[width * (i + 1) + j] += 3 * e / 8
                } else if (j < width - 1 && i == height - 1) {
                    //右邊像素處理
                    gray[width * i + j + 1] += e / 4
                }
            }
        }
        val mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
        mBitmap.setPixels(pixels, 0, width, 0, 0, width, height)
        imageView5.setImageBitmap(mBitmap)
        saveBmp(mBitmap)
        return mBitmap
    }
效果圖

現(xiàn)在的效果達(dá)到了要求潮秘,后面可以把它轉(zhuǎn)成單色圖,通過傳每一個像素給藍(lán)牙設(shè)備顯示出來易结。

轉(zhuǎn)成bmp圖片枕荞,保存到手機(jī)

    /**
     * 將Bitmap存為 .bmp格式圖片
     * @param bitmap
     */
    private fun saveBmp(bitmap: Bitmap?) {
        if (bitmap == null)
            return
        // 位圖大小
        val nBmpWidth = bitmap.width
        val nBmpHeight = bitmap.height
        // 圖像數(shù)據(jù)大小
        val bufferSize = nBmpHeight * (nBmpWidth * 3 + nBmpWidth % 4)
        try {
            // 存儲文件名
            val filename = "/sdcard/test${Random.nextInt(1000)}.bmp"
            val file = File(filename)
            if (!file.exists()) {
                file.createNewFile()
            }
            val fileos = FileOutputStream(filename)
            // bmp文件頭
            val bfType = 0x4d42
            val bfSize = (14 + 40 + bufferSize).toLong()
            val bfReserved1 = 0
            val bfReserved2 = 0
            val bfOffBits = (14 + 40).toLong()
            // 保存bmp文件頭
            writeWord(fileos, bfType)
            writeDword(fileos, bfSize)
            writeWord(fileos, bfReserved1)
            writeWord(fileos, bfReserved2)
            writeDword(fileos, bfOffBits)
            // bmp信息頭
            val biSize = 40L
            val biWidth = nBmpWidth.toLong()
            val biHeight = nBmpHeight.toLong()
            val biPlanes = 1
            val biBitCount = 24
            val biCompression = 0L
            val biSizeImage = 0L
            val biXpelsPerMeter = 0L
            val biYPelsPerMeter = 0L
            val biClrUsed = 0L
            val biClrImportant = 0L
            // 保存bmp信息頭
            writeDword(fileos, biSize)
            writeLong(fileos, biWidth)
            writeLong(fileos, biHeight)
            writeWord(fileos, biPlanes)
            writeWord(fileos, biBitCount)
            writeDword(fileos, biCompression)
            writeDword(fileos, biSizeImage)
            writeLong(fileos, biXpelsPerMeter)
            writeLong(fileos, biYPelsPerMeter)
            writeDword(fileos, biClrUsed)
            writeDword(fileos, biClrImportant)
            // 像素掃描
            val bmpData = ByteArray(bufferSize)
            val wWidth = nBmpWidth * 3 + nBmpWidth % 4
            var nCol = 0
            var nRealCol = nBmpHeight - 1
            while (nCol < nBmpHeight) {
                run {
                    var wRow = 0
                    var wByteIdex = 0
                    while (wRow < nBmpWidth) {
                        val clr = bitmap.getPixel(wRow, nCol)
                        bmpData[nRealCol * wWidth + wByteIdex] = Color.blue(clr).toByte()
                        bmpData[nRealCol * wWidth + wByteIdex + 1] = Color.green(clr).toByte()
                        bmpData[nRealCol * wWidth + wByteIdex + 2] = Color.red(clr).toByte()
                        wRow++
                        wByteIdex += 3
                    }
                }
                ++nCol
                --nRealCol
            }

            fileos.write(bmpData)
            fileos.flush()
            fileos.close()

        } catch (e: FileNotFoundException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }

    }

    @Throws(IOException::class)
    protected fun writeWord(stream: FileOutputStream, value: Int) {
        val b = ByteArray(2)
        b[0] = (value and 0xff).toByte()
        b[1] = (value shr 8 and 0xff).toByte()
        stream.write(b)
    }

    @Throws(IOException::class)
    protected fun writeDword(stream: FileOutputStream, value: Long) {
        val b = ByteArray(4)
        b[0] = (value and 0xff).toByte()
        b[1] = (value shr 8 and 0xff).toByte()
        b[2] = (value shr 16 and 0xff).toByte()
        b[3] = (value shr 24 and 0xff).toByte()
        stream.write(b)
    }

    @Throws(IOException::class)
    protected fun writeLong(stream: FileOutputStream, value: Long) {
        val b = ByteArray(4)
        b[0] = (value and 0xff).toByte()
        b[1] = (value shr 8 and 0xff).toByte()
        b[2] = (value shr 16 and 0xff).toByte()
        b[3] = (value shr 24 and 0xff).toByte()
        stream.write(b)
    }

End柜候!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市躏精,隨后出現(xiàn)的幾起案子渣刷,更是在濱河造成了極大的恐慌,老刑警劉巖矗烛,帶你破解...
    沈念sama閱讀 218,941評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件辅柴,死亡現(xiàn)場離奇詭異,居然都是意外死亡瞭吃,警方通過查閱死者的電腦和手機(jī)碌嘀,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來虱而,“玉大人筏餐,你說我怎么就攤上這事∧的矗” “怎么了魁瞪?”我有些...
    開封第一講書人閱讀 165,345評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長惠呼。 經(jīng)常有香客問我导俘,道長,這世上最難降的妖魔是什么剔蹋? 我笑而不...
    開封第一講書人閱讀 58,851評論 1 295
  • 正文 為了忘掉前任旅薄,我火速辦了婚禮,結(jié)果婚禮上泣崩,老公的妹妹穿的比我還像新娘少梁。我一直安慰自己,他們只是感情好矫付,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評論 6 392
  • 文/花漫 我一把揭開白布凯沪。 她就那樣靜靜地躺著,像睡著了一般买优。 火紅的嫁衣襯著肌膚如雪妨马。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評論 1 305
  • 那天杀赢,我揣著相機(jī)與錄音烘跺,去河邊找鬼。 笑死脂崔,一個胖子當(dāng)著我的面吹牛滤淳,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播砌左,決...
    沈念sama閱讀 40,414評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼娇钱,長吁一口氣:“原來是場噩夢啊……” “哼伤柄!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起文搂,我...
    開封第一講書人閱讀 39,319評論 0 276
  • 序言:老撾萬榮一對情侶失蹤适刀,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后煤蹭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體笔喉,經(jīng)...
    沈念sama閱讀 45,775評論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評論 3 336
  • 正文 我和宋清朗相戀三年硝皂,在試婚紗的時候發(fā)現(xiàn)自己被綠了常挚。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,096評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡稽物,死狀恐怖奄毡,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情贝或,我是刑警寧澤吼过,帶...
    沈念sama閱讀 35,789評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站咪奖,受9級特大地震影響盗忱,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜羊赵,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評論 3 331
  • 文/蒙蒙 一趟佃、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧昧捷,春花似錦闲昭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至芹血,卻和暖如春贮泞,著一層夾襖步出監(jiān)牢的瞬間楞慈,已是汗流浹背幔烛。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評論 1 271
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留囊蓝,地道東北人饿悬。 一個月前我還...
    沈念sama閱讀 48,308評論 3 372
  • 正文 我出身青樓,卻偏偏與公主長得像聚霜,于是被迫代替她去往敵國和親狡恬。 傳聞我的和親對象是個殘疾皇子珠叔,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評論 2 355

推薦閱讀更多精彩內(nèi)容