diff --git a/zxinglib/src/main/java/pony/xcode/zxing/AmbientLightManager.java b/zxinglib/src/main/java/pony/xcode/zxing/AmbientLightManager.java index 247c28d..32b8d66 100644 --- a/zxinglib/src/main/java/pony/xcode/zxing/AmbientLightManager.java +++ b/zxinglib/src/main/java/pony/xcode/zxing/AmbientLightManager.java @@ -42,6 +42,7 @@ final class AmbientLightManager implements SensorEventListener { private final Context context; private CameraManager cameraManager; + private SensorManager sensorManager; private Sensor lightSensor; AmbientLightManager(Context context) { @@ -52,9 +53,9 @@ void start(CameraManager cameraManager) { this.cameraManager = cameraManager; SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); if (FrontLightMode.readPref(sharedPrefs) == FrontLightMode.AUTO) { - SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); - lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); - if (lightSensor != null) { + sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); + if (sensorManager != null) { + lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); sensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL); } } @@ -62,9 +63,11 @@ void start(CameraManager cameraManager) { void stop() { if (lightSensor != null) { - SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); - sensorManager.unregisterListener(this); + if (sensorManager != null) { + sensorManager.unregisterListener(this); + } cameraManager = null; + sensorManager = null; lightSensor = null; } } diff --git a/zxinglib/src/main/java/pony/xcode/zxing/BeepManager.java b/zxinglib/src/main/java/pony/xcode/zxing/BeepManager.java index 079048d..0bb7a77 100644 --- a/zxinglib/src/main/java/pony/xcode/zxing/BeepManager.java +++ b/zxinglib/src/main/java/pony/xcode/zxing/BeepManager.java @@ -90,32 +90,21 @@ synchronized void playBeepSoundAndVibrate() { // } private MediaPlayer buildMediaPlayer() { - MediaPlayer mediaPlayer = MediaPlayer.create(activity, R.raw.zxl_beep); + MediaPlayer mediaPlayer = null; try { + mediaPlayer = MediaPlayer.create(activity, R.raw.zxl_beep); mediaPlayer.setOnErrorListener(this); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setLooping(false); mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); -// mediaPlayer.prepare(); return mediaPlayer; } catch (Exception e) { Log.w(TAG, e); - mediaPlayer.release(); + if (mediaPlayer != null) { + mediaPlayer.release(); + } return null; } -// try (AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.zxl_beep)) { -// mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); -// mediaPlayer.setOnErrorListener(this); -// mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); -// mediaPlayer.setLooping(false); -// mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); -// mediaPlayer.prepare(); -// return mediaPlayer; -// } catch (IOException ioe) { -// Log.w(TAG, ioe); -// mediaPlayer.release(); -// return null; -// } } @Override diff --git a/zxinglib/src/main/java/pony/xcode/zxing/CaptureFragment.java b/zxinglib/src/main/java/pony/xcode/zxing/CaptureFragment.java index 3f79af4..5c1addb 100644 --- a/zxinglib/src/main/java/pony/xcode/zxing/CaptureFragment.java +++ b/zxinglib/src/main/java/pony/xcode/zxing/CaptureFragment.java @@ -21,6 +21,7 @@ import android.view.View; import android.view.ViewGroup; +import androidx.annotation.IdRes; import androidx.annotation.LayoutRes; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -36,15 +37,12 @@ public class CaptureFragment extends Fragment implements OnCaptureCallback { private View mRootView; - private SurfaceView surfaceView; - private ViewfinderView viewfinderView; - private CaptureHelper mCaptureHelper; public static CaptureFragment newInstance() { Bundle args = new Bundle(); - + CaptureFragment fragment = new CaptureFragment(); fragment.setArguments(args); return fragment; @@ -54,8 +52,8 @@ public static CaptureFragment newInstance() { @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { int layoutId = getLayoutId(); - if(isContentView(layoutId)){ - mRootView = inflater.inflate(getLayoutId(),container,false); + if (isContentView(layoutId)) { + mRootView = inflater.inflate(getLayoutId(), container, false); } initUI(); return mRootView; @@ -64,60 +62,64 @@ public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, /** * 初始化 */ - public void initUI(){ - surfaceView = mRootView.findViewById(getSurfaceViewId()); - viewfinderView = mRootView.findViewById(getViewfinderViewId()); - mCaptureHelper = new CaptureHelper(this,surfaceView,viewfinderView); + public void initUI() { + SurfaceView surfaceView = mRootView.findViewById(getSurfaceViewId()); + ViewfinderView viewfinderView = mRootView.findViewById(getViewfinderViewId()); + mCaptureHelper = new CaptureHelper(this, surfaceView, viewfinderView); mCaptureHelper.setOnCaptureCallback(this); } /** * 返回true时会自动初始化{@link #mRootView},返回为false时需自己去通过{@link #setRootView(View)}初始化{@link #mRootView} - * @param layoutId + * * @return 默认返回true */ - public boolean isContentView(@LayoutRes int layoutId){ + public boolean isContentView(@LayoutRes int layoutId) { return true; } /** * 布局id + * * @return */ - public int getLayoutId(){ + @LayoutRes + public int getLayoutId() { return R.layout.zxl_capture; } /** * {@link ViewfinderView} 的 id - * @return */ - public int getViewfinderViewId(){ + @IdRes + public int getViewfinderViewId() { return R.id.viewfinderView; } /** - * 预览界面{@link #surfaceView} 的id - * @return + * 预览界面{@link SurfaceView} 的id */ - public int getSurfaceViewId(){ + @IdRes + public int getSurfaceViewId() { return R.id.surfaceView; } /** * Get {@link CaptureHelper} + * * @return {@link #mCaptureHelper} */ - public CaptureHelper getCaptureHelper(){ + public CaptureHelper getCaptureHelper() { return mCaptureHelper; } /** * Get {@link CameraManager} + * * @return {@link #mCaptureHelper#getCameraManager()} */ - public CameraManager getCameraManager(){ + public CameraManager getCameraManager() { return mCaptureHelper.getCameraManager(); } @@ -159,6 +161,7 @@ public void onDestroy() { /** * 接收扫码结果回调 + * * @param result 扫码结果 * @return 返回true表示拦截,将不自动执行后续逻辑,为false表示不拦截,默认不拦截 */ diff --git a/zxinglib/src/main/java/pony/xcode/zxing/DecodeHandler.java b/zxinglib/src/main/java/pony/xcode/zxing/DecodeHandler.java index 24718fa..fca5d3c 100644 --- a/zxinglib/src/main/java/pony/xcode/zxing/DecodeHandler.java +++ b/zxinglib/src/main/java/pony/xcode/zxing/DecodeHandler.java @@ -28,6 +28,8 @@ import android.view.Display; import android.view.WindowManager; +import androidx.annotation.NonNull; + import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; @@ -55,7 +57,7 @@ final class DecodeHandler extends Handler { private long lastZoomTime; - DecodeHandler(Context context, CameraManager cameraManager,CaptureHandler handler, Map hints) { + DecodeHandler(Context context, CameraManager cameraManager, CaptureHandler handler, Map hints) { multiFormatReader = new MultiFormatReader(); multiFormatReader.setHints(hints); this.context = context; @@ -64,21 +66,23 @@ final class DecodeHandler extends Handler { } @Override - public void handleMessage(Message message) { - if (message == null || !running) { + public void handleMessage(@NonNull Message message) { + if (!running) { return; } if (message.what == R.id.decode) { - decode((byte[]) message.obj, message.arg1, message.arg2,isScreenPortrait(),handler.isSupportVerticalCode()); + decode((byte[]) message.obj, message.arg1, message.arg2, isScreenPortrait(), handler.isSupportVerticalCode()); } else if (message.what == R.id.quit) { running = false; - Looper.myLooper().quit(); - + Looper looper = Looper.myLooper(); + if (looper != null) { + looper.quit(); + } } } - private boolean isScreenPortrait(){ + private boolean isScreenPortrait() { WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); Display display = manager.getDefaultDisplay(); Point screenResolution = new Point(); @@ -94,10 +98,10 @@ private boolean isScreenPortrait(){ * @param width The width of the preview frame. * @param height The height of the preview frame. */ - private void decode(byte[] data, int width, int height,boolean isScreenPortrait,boolean isSupportVerticalCode) { + private void decode(byte[] data, int width, int height, boolean isScreenPortrait, boolean isSupportVerticalCode) { long start = System.currentTimeMillis(); Result rawResult = null; - PlanarYUVLuminanceSource source = buildPlanarYUVLuminanceSource(data,width,height,isScreenPortrait); + PlanarYUVLuminanceSource source = buildPlanarYUVLuminanceSource(data, width, height, isScreenPortrait); if (source != null) { BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); @@ -105,16 +109,16 @@ private void decode(byte[] data, int width, int height,boolean isScreenPortrait, rawResult = multiFormatReader.decodeWithState(bitmap); } catch (Exception e) { BinaryBitmap bitmap1 = new BinaryBitmap(new GlobalHistogramBinarizer(source)); - try{ + try { rawResult = multiFormatReader.decodeWithState(bitmap1); - }catch (Exception e1){ - if(isSupportVerticalCode){ - source = buildPlanarYUVLuminanceSource(data,width,height,!isScreenPortrait); - if(source!=null){ + } catch (Exception e1) { + if (isSupportVerticalCode) { + source = buildPlanarYUVLuminanceSource(data, width, height, !isScreenPortrait); + if (source != null) { BinaryBitmap bitmap2 = new BinaryBitmap(new HybridBinarizer(source)); - try{ + try { rawResult = multiFormatReader.decodeWithState(bitmap2); - }catch (Exception e2){ + } catch (Exception ignored) { } } @@ -133,24 +137,24 @@ private void decode(byte[] data, int width, int height,boolean isScreenPortrait, Log.d(TAG, "Found barcode in " + (end - start) + " ms"); BarcodeFormat barcodeFormat = rawResult.getBarcodeFormat(); - if(handler!=null && handler.isSupportAutoZoom() && barcodeFormat == BarcodeFormat.QR_CODE){ + if (handler != null && handler.isSupportAutoZoom() && barcodeFormat == BarcodeFormat.QR_CODE) { ResultPoint[] resultPoints = rawResult.getResultPoints(); - if(resultPoints.length >= 3){ - float distance1 = ResultPoint.distance(resultPoints[0],resultPoints[1]); - float distance2 = ResultPoint.distance(resultPoints[1],resultPoints[2]); - float distance3 = ResultPoint.distance(resultPoints[0],resultPoints[2]); - int maxDistance = (int)Math.max(Math.max(distance1,distance2),distance3); - if(handleAutoZoom(maxDistance,width)){ + if (resultPoints.length >= 3) { + float distance1 = ResultPoint.distance(resultPoints[0], resultPoints[1]); + float distance2 = ResultPoint.distance(resultPoints[1], resultPoints[2]); + float distance3 = ResultPoint.distance(resultPoints[0], resultPoints[2]); + int maxDistance = (int) Math.max(Math.max(distance1, distance2), distance3); + if (handleAutoZoom(maxDistance, width)) { Message message = Message.obtain(); message.what = R.id.decode_succeeded; message.obj = rawResult; - if(handler.isReturnBitmap()){ + if (handler.isReturnBitmap()) { Bundle bundle = new Bundle(); bundleThumbnail(source, bundle); message.setData(bundle); } - handler.sendMessageDelayed(message,300); + handler.sendMessageDelayed(message, 300); return; } } @@ -160,7 +164,7 @@ private void decode(byte[] data, int width, int height,boolean isScreenPortrait, if (handler != null) { Message message = Message.obtain(handler, R.id.decode_succeeded, rawResult); - if(handler.isReturnBitmap()){ + if (handler.isReturnBitmap()) { Bundle bundle = new Bundle(); bundleThumbnail(source, bundle); message.setData(bundle); @@ -175,9 +179,9 @@ private void decode(byte[] data, int width, int height,boolean isScreenPortrait, } } - private PlanarYUVLuminanceSource buildPlanarYUVLuminanceSource(byte[] data, int width, int height,boolean isRotate){ + private PlanarYUVLuminanceSource buildPlanarYUVLuminanceSource(byte[] data, int width, int height, boolean isRotate) { PlanarYUVLuminanceSource source; - if(isRotate){ + if (isRotate) { byte[] rotatedData = new byte[data.length]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) @@ -187,7 +191,7 @@ private PlanarYUVLuminanceSource buildPlanarYUVLuminanceSource(byte[] data, int width = height; height = tmp; source = cameraManager.buildLuminanceSource(rotatedData, width, height); - }else{ + } else { source = cameraManager.buildLuminanceSource(data, width, height); } return source; @@ -204,20 +208,20 @@ private static void bundleThumbnail(PlanarYUVLuminanceSource source, Bundle bund bundle.putFloat(DecodeThread.BARCODE_SCALED_FACTOR, (float) width / source.getWidth()); } - private boolean handleAutoZoom(int length,int width){ - if(lastZoomTime > System.currentTimeMillis() - 1000){ + private boolean handleAutoZoom(int length, int width) { + if (lastZoomTime > System.currentTimeMillis() - 1000) { return true; } - if(length private WeakReference weakReference; - public InactivityAsyncTask(Activity activity){ + InactivityAsyncTask(Activity activity){ weakReference = new WeakReference<>(activity); } diff --git a/zxinglib/src/main/java/pony/xcode/zxing/Intents.java b/zxinglib/src/main/java/pony/xcode/zxing/Intents.java index 2504001..20fec0f 100644 --- a/zxinglib/src/main/java/pony/xcode/zxing/Intents.java +++ b/zxinglib/src/main/java/pony/xcode/zxing/Intents.java @@ -120,7 +120,6 @@ public static final class Scan { /** * If a barcode is found, Barcodes returns {@link android.app.Activity#RESULT_OK} to - * {@link android.app.Activity#onActivityResult(int, int, Intent)} * of the app which requested the scan via * {@link android.app.Activity#startActivityForResult(Intent, int)} * The barcodes contents can be retrieved with diff --git a/zxinglib/src/main/java/pony/xcode/zxing/camera/AutoFocusManager.java b/zxinglib/src/main/java/pony/xcode/zxing/camera/AutoFocusManager.java index f345096..32cc7c4 100644 --- a/zxinglib/src/main/java/pony/xcode/zxing/camera/AutoFocusManager.java +++ b/zxinglib/src/main/java/pony/xcode/zxing/camera/AutoFocusManager.java @@ -121,7 +121,7 @@ private static class AutoFocusTask extends AsyncTask { private WeakReference weakReference; - public AutoFocusTask(AutoFocusManager manager){ + AutoFocusTask(AutoFocusManager manager){ weakReference = new WeakReference<>(manager); } diff --git a/zxinglib/src/main/java/pony/xcode/zxing/camera/CameraConfigurationManager.java b/zxinglib/src/main/java/pony/xcode/zxing/camera/CameraConfigurationManager.java index 7454dc6..b390642 100644 --- a/zxinglib/src/main/java/pony/xcode/zxing/camera/CameraConfigurationManager.java +++ b/zxinglib/src/main/java/pony/xcode/zxing/camera/CameraConfigurationManager.java @@ -36,7 +36,6 @@ * A class which deals with reading, parsing, and setting the camera parameters which are used to * configure the camera hardware. */ -@SuppressWarnings("deprecation") // camera APIs final class CameraConfigurationManager { private static final String TAG = "CameraConfiguration"; diff --git a/zxinglib/src/main/java/pony/xcode/zxing/camera/CameraConfigurationUtils.java b/zxinglib/src/main/java/pony/xcode/zxing/camera/CameraConfigurationUtils.java index d2ef8ed..1b2e0ae 100644 --- a/zxinglib/src/main/java/pony/xcode/zxing/camera/CameraConfigurationUtils.java +++ b/zxinglib/src/main/java/pony/xcode/zxing/camera/CameraConfigurationUtils.java @@ -194,12 +194,16 @@ private static List buildMiddleArea(int areaPer1000) { } public static void setVideoStabilization(Camera.Parameters parameters) { - if (parameters.isVideoStabilizationSupported()) { - if (parameters.getVideoStabilization()) { - Log.i(TAG, "Video stabilization already enabled"); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { + if (parameters.isVideoStabilizationSupported()) { + if (parameters.getVideoStabilization()) { + Log.i(TAG, "Video stabilization already enabled"); + } else { + Log.i(TAG, "Enabling video stabilization..."); + parameters.setVideoStabilization(true); + } } else { - Log.i(TAG, "Enabling video stabilization..."); - parameters.setVideoStabilization(true); + Log.i(TAG, "This device does not support video stabilization"); } } else { Log.i(TAG, "This device does not support video stabilization"); @@ -271,7 +275,7 @@ public static void setInvertColor(Camera.Parameters parameters) { } } - public static Point findBestPreviewSizeValue(Camera.Parameters parameters,final Point screenResolution) { + public static Point findBestPreviewSizeValue(Camera.Parameters parameters, final Point screenResolution) { List rawSupportedSizes = parameters.getSupportedPreviewSizes(); if (rawSupportedSizes == null) { @@ -293,9 +297,9 @@ public static Point findBestPreviewSizeValue(Camera.Parameters parameters,final } double screenAspectRatio; - if(screenResolution.x < screenResolution.y){ + if (screenResolution.x < screenResolution.y) { screenAspectRatio = screenResolution.x / (double) screenResolution.y; - }else{ + } else { screenAspectRatio = screenResolution.y / (double) screenResolution.x; } Log.i(TAG, "screenAspectRatio: " + screenAspectRatio); @@ -312,9 +316,9 @@ public static Point findBestPreviewSizeValue(Camera.Parameters parameters,final } boolean isCandidatePortrait = realWidth < realHeight; - int maybeFlippedWidth = isCandidatePortrait ? realWidth: realHeight ; + int maybeFlippedWidth = isCandidatePortrait ? realWidth : realHeight; int maybeFlippedHeight = isCandidatePortrait ? realHeight : realWidth; - Log.i(TAG, String.format("maybeFlipped:%d * %d",maybeFlippedWidth,maybeFlippedHeight)); + Log.i(TAG, String.format("maybeFlipped:%d * %d", maybeFlippedWidth, maybeFlippedHeight)); double aspectRatio = maybeFlippedWidth / (double) maybeFlippedHeight; Log.i(TAG, "aspectRatio: " + aspectRatio); diff --git a/zxinglib/src/main/java/pony/xcode/zxing/util/CodeUtils.java b/zxinglib/src/main/java/pony/xcode/zxing/util/CodeUtils.java index 3d2c245..634f2a0 100644 --- a/zxinglib/src/main/java/pony/xcode/zxing/util/CodeUtils.java +++ b/zxinglib/src/main/java/pony/xcode/zxing/util/CodeUtils.java @@ -55,47 +55,35 @@ */ public class CodeUtils { - private CodeUtils(){ + private CodeUtils() { throw new AssertionError(); } /** * 生成二维码 - * @param content - * @param heightPix - * @return */ public static Bitmap createQRCode(String content, int heightPix) { - return createQRCode(content,heightPix,null); + return createQRCode(content, heightPix, null); } /** * 生成二维码 - * @param content - * @param heightPix - * @param logo - * @return */ public static Bitmap createQRCode(String content, int heightPix, Bitmap logo) { //配置参数 Map hints = new HashMap<>(); - hints.put( EncodeHintType.CHARACTER_SET, "utf-8"); + hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //容错级别 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //设置空白边距的宽度 hints.put(EncodeHintType.MARGIN, 1); //default is 4 - return createQRCode(content,heightPix,logo,hints); + return createQRCode(content, heightPix, logo, hints); } /** * 生成二维码 - * @param content - * @param heightPix - * @param logo - * @param hints - * @return */ - public static Bitmap createQRCode(String content, int heightPix, Bitmap logo,Map hints) { + public static Bitmap createQRCode(String content, int heightPix, Bitmap logo, Map hints) { try { // 图像数据转换,使用了矩阵转换 @@ -175,44 +163,39 @@ private static Bitmap addLogo(Bitmap src, Bitmap logo) { /** * 解析二维码图片 - * @param bitmapPath - * @return */ public static String parseQRCode(String bitmapPath) { Map hints = new HashMap<>(); hints.put(DecodeHintType.CHARACTER_SET, "utf-8"); - return parseQRCode(bitmapPath,hints); + return parseQRCode(bitmapPath, hints); } /** * 解析二维码图片 - * @param bitmapPath - * @param hints - * @return */ - public static String parseQRCode(String bitmapPath, Map hints){ + public static String parseQRCode(String bitmapPath, Map hints) { try { QRCodeReader reader = new QRCodeReader(); Result result = null; RGBLuminanceSource source = getRGBLuminanceSource(compressBitmap(bitmapPath)); - if (source != null) { - BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); + BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); + try { + result = reader.decode(bitmap, hints); + } catch (Exception e) { + //解析失败则通过GlobalHistogramBinarizer 再试一次 + BinaryBitmap bitmap1 = new BinaryBitmap(new GlobalHistogramBinarizer(source)); try { - result = reader.decode(bitmap,hints); - } catch (Exception e) { - //解析失败则通过GlobalHistogramBinarizer 再试一次 - BinaryBitmap bitmap1 = new BinaryBitmap(new GlobalHistogramBinarizer(source)); - try { - result = reader.decode(bitmap1); - } catch (NotFoundException ne) { + result = reader.decode(bitmap1); + } catch (NotFoundException ignored) { - } - } finally { - reader.reset(); } + } finally { + reader.reset(); + } + if (result != null) { + return result.getText(); } - return result.getText(); } catch (Exception e) { e.printStackTrace(); @@ -222,11 +205,9 @@ public static String parseQRCode(String bitmapPath, Map hints) /** * 解析一维码/二维码图片 - * @param bitmapPath - * @return */ - public static String parseCode(String bitmapPath){ - Map hints = new HashMap<>(); + public static String parseCode(String bitmapPath) { + Map hints = new HashMap<>(); //添加可以解析的编码类型 Vector decodeFormats = new Vector<>(); decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS); @@ -235,40 +216,40 @@ public static String parseCode(String bitmapPath){ decodeFormats.addAll(DecodeFormatManager.AZTEC_FORMATS); decodeFormats.addAll(DecodeFormatManager.PDF417_FORMATS); - hints.put(DecodeHintType.TRY_HARDER,Boolean.TRUE); + hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats); - return parseCode(bitmapPath,hints); + return parseCode(bitmapPath, hints); } /** * 解析一维码/二维码图片 + * * @param bitmapPath - * @param hints 解析编码类型 + * @param hints 解析编码类型 * @return */ - public static String parseCode(String bitmapPath, Map hints){ + public static String parseCode(String bitmapPath, Map hints) { try { MultiFormatReader reader = new MultiFormatReader(); reader.setHints(hints); Result result = null; RGBLuminanceSource source = getRGBLuminanceSource(compressBitmap(bitmapPath)); - if (source != null) { - BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); + BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); + try { + result = reader.decodeWithState(bitmap); + } catch (Exception e) {//解析失败则通过GlobalHistogramBinarizer 再试一次 + BinaryBitmap bitmap1 = new BinaryBitmap(new GlobalHistogramBinarizer(source)); try { - result = reader.decodeWithState(bitmap); - } catch (Exception e) {//解析失败则通过GlobalHistogramBinarizer 再试一次 - BinaryBitmap bitmap1 = new BinaryBitmap(new GlobalHistogramBinarizer(source)); - try { - result = reader.decodeWithState(bitmap1); - } catch (Exception ne) { + result = reader.decodeWithState(bitmap1); + } catch (Exception ignored) { - } - } finally { - reader.reset(); } + } finally { + reader.reset(); } - return result.getText(); + if (result != null) + return result.getText(); } catch (Exception e) { e.printStackTrace(); } @@ -276,13 +257,10 @@ public static String parseCode(String bitmapPath, Map hin } - /** * 压缩图片 - * @param path - * @return */ - private static Bitmap compressBitmap(String path){ + private static Bitmap compressBitmap(String path) { BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 @@ -309,10 +287,8 @@ private static Bitmap compressBitmap(String path){ /** * 获取RGBLuminanceSource - * @param bitmap - * @return */ - private static RGBLuminanceSource getRGBLuminanceSource(@NonNull Bitmap bitmap){ + private static RGBLuminanceSource getRGBLuminanceSource(@NonNull Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); @@ -324,58 +300,31 @@ private static RGBLuminanceSource getRGBLuminanceSource(@NonNull Bitmap bitmap){ /** * 生成条形码 - * @param content - * @param format - * @param desiredWidth - * @param desiredHeight - * @return */ - public static Bitmap createBarCode(String content,BarcodeFormat format, int desiredWidth, int desiredHeight) { - return createBarCode(content,format,desiredWidth,desiredHeight,null); + public static Bitmap createBarCode(String content, BarcodeFormat format, int desiredWidth, int desiredHeight) { + return createBarCode(content, format, desiredWidth, desiredHeight, null); } /** * 生成条形码 - * @param content - * @param format - * @param desiredWidth - * @param desiredHeight - * @param hints - * @return */ - public static Bitmap createBarCode(String content, BarcodeFormat format, int desiredWidth, int desiredHeight, Map hints) { - return createBarCode(content,format,desiredWidth,desiredHeight,hints,false,40,Color.BLACK); + public static Bitmap createBarCode(String content, BarcodeFormat format, int desiredWidth, int desiredHeight, Map hints) { + return createBarCode(content, format, desiredWidth, desiredHeight, hints, false, 40, Color.BLACK); } /** * 生成条形码 - * @param content - * @param format - * @param desiredWidth - * @param desiredHeight - * @param hints - * @param isShowText - * @return */ - public static Bitmap createBarCode(String content, BarcodeFormat format, int desiredWidth, int desiredHeight, Map hints, boolean isShowText) { - return createBarCode(content,format,desiredWidth,desiredHeight,hints,isShowText,40,Color.BLACK); + public static Bitmap createBarCode(String content, BarcodeFormat format, int desiredWidth, int desiredHeight, Map hints, boolean isShowText) { + return createBarCode(content, format, desiredWidth, desiredHeight, hints, isShowText, 40, Color.BLACK); } /** * 生成条形码 - * @param content - * @param format - * @param desiredWidth - * @param desiredHeight - * @param hints - * @param isShowText - * @param textSize - * @param textColor - * @return */ - public static Bitmap createBarCode(String content,BarcodeFormat format, int desiredWidth, int desiredHeight,Map hints,boolean isShowText,int textSize,@ColorInt int textColor) { - if(TextUtils.isEmpty(content)){ + public static Bitmap createBarCode(String content, BarcodeFormat format, int desiredWidth, int desiredHeight, Map hints, boolean isShowText, int textSize, @ColorInt int textColor) { + if (TextUtils.isEmpty(content)) { return null; } final int WHITE = 0xFFFFFFFF; @@ -399,8 +348,8 @@ public static Bitmap createBarCode(String content,BarcodeFormat format, int desi Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); - if(isShowText){ - return addCode(bitmap,content,textSize,textColor,textSize/2); + if (isShowText) { + return addCode(bitmap, content, textSize, textColor, textSize / 2); } return bitmap; } catch (WriterException e) { @@ -411,13 +360,8 @@ public static Bitmap createBarCode(String content,BarcodeFormat format, int desi /** * 条形码下面添加文本信息 - * @param src - * @param code - * @param textSize - * @param textColor - * @return */ - private static Bitmap addCode(Bitmap src,String code,int textSize,@ColorInt int textColor,int offset) { + private static Bitmap addCode(Bitmap src, String code, int textSize, @ColorInt int textColor, int offset) { if (src == null) { return null; } @@ -442,7 +386,7 @@ private static Bitmap addCode(Bitmap src,String code,int textSize,@ColorInt int paint.setTextSize(textSize); paint.setColor(textColor); paint.setTextAlign(Paint.Align.CENTER); - canvas.drawText(code,srcWidth/2,srcHeight + textSize /2 + offset,paint); + canvas.drawText(code, srcWidth / 2, srcHeight + textSize / 2f + offset, paint); canvas.save(); canvas.restore(); } catch (Exception e) {