Skip to content

Commit

Permalink
Fix integer overflow bug in Downsampler when asked to upscale images.
Browse files Browse the repository at this point in the history
This should also be a slight accuracy improvement since we're now using
a somewhat more efficient density multiplier in some cases, especially
when downsampling.

Fixes #2459.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=171601510
  • Loading branch information
sjudd committed Oct 10, 2017
1 parent 762fd37 commit c7383b2
Showing 1 changed file with 10 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ static void calculateScaling(
// densities here so we calculate the final Bitmap size correctly.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
options.inTargetDensity = adjustTargetDensityForError(adjustedScaleFactor);
options.inDensity = DENSITY_PRECISION_MULTIPLIER;
options.inDensity = getDensityMultiplier(adjustedScaleFactor);
}
if (isScaling(options)) {
options.inScaled = true;
Expand All @@ -473,12 +473,19 @@ static void calculateScaling(
* the final scale factor is as close to our target as possible.
*/
private static int adjustTargetDensityForError(double adjustedScaleFactor) {
int targetDensity = round(DENSITY_PRECISION_MULTIPLIER * adjustedScaleFactor);
float scaleFactorWithError = targetDensity / (float) DENSITY_PRECISION_MULTIPLIER;
int densityMultiplier = getDensityMultiplier(adjustedScaleFactor);
int targetDensity = round(densityMultiplier * adjustedScaleFactor);
float scaleFactorWithError = targetDensity / (float) densityMultiplier;
double difference = adjustedScaleFactor / scaleFactorWithError;
return round(difference * targetDensity);
}

private static int getDensityMultiplier(double adjustedScaleFactor) {
return (int) Math.round(
Integer.MAX_VALUE
* (adjustedScaleFactor <= 1D ? adjustedScaleFactor : 1 / adjustedScaleFactor));
}

// This is weird, but it matches the logic in a bunch of Android views/framework classes for
// rounding.
private static int round(double value) {
Expand Down

0 comments on commit c7383b2

Please sign in to comment.